Beispiel #1
0
int setbuf(FILE *stream,char *buf)
{ return setvbuf(stream,buf,buf?_IOFBF:_IONBF,BUFSIZ); }
Beispiel #2
0
void printf_init()
{
  setvbuf(stdout, NULL, _IOFBF, IOV_MAX);
}
Beispiel #3
0
// -----------------------------------------------------------------
//
// @details This is the entry point for the Win32 application.
//
// -----------------------------------------------------------------
int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nShowCmd)
{
	//
	// Create a console window for debugging and other output
	AllocConsole();

	HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
	int hcrt = _open_osfhandle((long) hout, _O_TEXT);
	FILE* fout = _fdopen(hcrt, "w");
	setvbuf(fout, NULL, _IONBF, 1);
	*stdout = *fout;

	HANDLE hin = GetStdHandle(STD_INPUT_HANDLE);
	hcrt = _open_osfhandle((long) hin, _O_TEXT);
	FILE* fin = _fdopen(hcrt, "r");
	setvbuf(fin, NULL, _IONBF, 128);
	*stdin = *fin;

	//
	// Define a window class
	WNDCLASS wcl;
	wcl.hInstance = hInstance;
	wcl.lpszClassName = L"FaultTolerant";
	wcl.lpfnWndProc = WinMessageHandler;
	wcl.cbClsExtra = 0;
	wcl.cbWndExtra = 0;

	wcl.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
	wcl.hIcon = LoadIcon(NULL, IDI_WINLOGO);
	wcl.hCursor = LoadCursor(NULL, IDC_ARROW);
	wcl.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
	wcl.lpszMenuName=NULL;

	//
	// Register with Windows
	if (!RegisterClass(&wcl)) 
	{
		return 0;
	}

	DWORD dwStyle = WS_OVERLAPPEDWINDOW | WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
	DWORD dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;

	//
	// Create the window
	HWND hwnd = CreateWindowEx(
		dwExStyle,
		L"FaultTolerant",
		L"FaultTolerantPriority - Demo",
		dwStyle,
		CW_USEDEFAULT,CW_USEDEFAULT,
		500, 500,
		NULL,
		NULL,
		hInstance,
		NULL);
	SetFocus(hwnd);

	//
	// Obtain the client size of the window
	RECT rcClient;
	GetClientRect(hwnd, &rcClient);

	//
	// Initialize the application code
	g_app = std::make_shared<FaultTolerantApp>(hwnd, static_cast<uint16_t>(rcClient.right), static_cast<uint16_t>(rcClient.bottom));
	g_app->initialize();
	//
	// Display the window
	ShowWindow(hwnd, nShowCmd);

	//
	// Enter the Windows message loop
	MSG winMessage;
	while (GetMessage(&winMessage,NULL,0,0))
	{
		TranslateMessage(&winMessage);
		DispatchMessage(&winMessage);

		g_app->pulse();
	}

	g_app->terminate();

	//
	// Disable a compiler warning complaining about WPARAM to int conversion.
	#pragma warning(push)
	#pragma warning(disable : 4244)
	return winMessage.wParam;
	#pragma warning(pop)
}
Beispiel #4
0
/*---------------------------------------------------------------------------*/
void
slip_init(void)
{
  setvbuf(stdout, NULL, _IOLBF, 0);     /* Line buffered output. */

  if(slip_config_host != NULL) {
    if(slip_config_port == NULL) {
      slip_config_port = "60001";
    }
    slipfd = connect_to_server(slip_config_host, slip_config_port);
    if(slipfd == -1) {
      LOG6LBR_FATAL("can't connect to %s:%s\n", slip_config_host,
          slip_config_port);
      exit(1);
    }

  } else if(slip_config_siodev != NULL) {
    if(strcmp(slip_config_siodev, "null") == 0) {
      /* Disable slip */
      return;
    }
    slipfd = devopen(slip_config_siodev, O_RDWR | O_NONBLOCK);
    if(slipfd == -1) {
      LOG6LBR_FATAL( "can't open siodev /dev/%s : %s\n", slip_config_siodev, strerror(errno));
      exit(1);
    }

  } else {
    static const char *siodevs[] = {
      "ttyUSB0", "cuaU0", "ucom0"       /* linux, fbsd6, fbsd5 */
    };
    int i;

    for(i = 0; i < 3; i++) {
      slip_config_siodev = siodevs[i];
      slipfd = devopen(slip_config_siodev, O_RDWR | O_NONBLOCK);
      if(slipfd != -1) {
        break;
      }
    }
    if(slipfd == -1) {
      LOG6LBR_FATAL("can't open siodev : %s\n", strerror(errno));
      exit(1);
    }
  }

  select_set_callback(slipfd, &slip_callback);

  if(slip_config_host != NULL) {
    LOG6LBR_INFO("SLIP opened to %s:%s\n", slip_config_host,
           slip_config_port);
  } else {
    LOG6LBR_INFO("SLIP started on /dev/%s\n", slip_config_siodev);
    stty_telos(slipfd);
  }

  timer_set(&send_delay_timer, 0);
  slip_send(slipfd, SLIP_END);
  inslip = fdopen(slipfd, "r");
  if(inslip == NULL) {
    LOG6LBR_FATAL("main: fdopen: %s\n", strerror(errno));
    exit(1);
  }
}
Beispiel #5
0
/* catread - read a catalogue file */
static _CAT_CATALOG_T *
catread (const char *name)
{
  FILE *f;
  STRING_T *s = DScreate (), *t = DScreate ();
  _CAT_CATALOG_T *cat = 0;
  size_t z;
  _CAT_MESSAGE_T catmsg = { 0, 0, 0 };
  int c;

  /* Open the catfile */
  f = fopen (name, "r");
  if (f == 0)
    return 0;			/* could not open file */
  setvbuf (f, 0, _IOFBF, 16384);
  while (DSlength (s = append_from_file (f, s)) > 0)
    {
      DSresize (s, DSlength (s) - 1, 0);
      /* We have a full line */
      if (DSlength (s) > 0)
	{
	  z = DSfind_first_not_of (s, " \t\f\v\r", 0, NPOS);
	  DSremove (s, 0, z);
	  z = DSfind_last_not_of (s, " \t\f\v\r", NPOS, NPOS);
	  DSresize (s, z + 1, 0);
	}
      if (DSlength (s) > 0 && DSget_at (s, DSlength (s) - 1) == '\\')
	{
	  /* continuation */
	  DSresize (s, DSlength (s) - 1, 0);
	}
      else
	{
	  if (DSlength (s) > 0 && isdigit (DSget_at (s, 0)))
	    {
	      /* if it starts with a digit, assume it's a catalog line */
	      for (z = 0, catmsg.set_id = 0;
		   isdigit (c = DSget_at (s, z));
		   catmsg.set_id = catmsg.set_id * 10 + (c - '0'), z++);
	      z++;
	      for (catmsg.msg_id = 0;
		   isdigit (c = DSget_at (s, z));
		   catmsg.msg_id = catmsg.msg_id * 10 + (c - '0'), z++);
	      z++;
	      DSremove (s, 0, z);
	      transform_string (t, s);
	      if (catmsg.msg == 0)
		catmsg.msg = DScreate ();
	      DSassign (catmsg.msg, t, 0, NPOS);
	      if (cat == 0)
		{
		  cat = malloc (sizeof (_CAT_CATALOG_T));
		  if (cat == 0)
		    Nomemory ();
		  cat->is_opened = 0;
		  cat->msgs = _CATMSG_create ();
		}
	      _CATMSG_append (cat->msgs, &catmsg, 1, 0);
	    }
	  DSresize (s, 0, 0);
	}
    }
  fclose (f);
  qsort (_CATMSG_base (cat->msgs), _CATMSG_length (cat->msgs),
	 sizeof (_CAT_MESSAGE_T), catmsg_cmp);
  return cat;
}
Beispiel #6
0
//int main(int argc, const char * argv[]) {
void VoxelServer::run() {
    
    const char VOXEL_SERVER_LOGGING_TARGET_NAME[] = "voxel-server";
    
    // change the logging target name while this is running
    Logging::setTargetName(VOXEL_SERVER_LOGGING_TARGET_NAME);

    // Now would be a good time to parse our arguments, if we got them as assignment
    if (getNumPayloadBytes() > 0) {
        parsePayload();
    }

    pthread_mutex_init(&_treeLock, NULL);
    
    qInstallMessageHandler(Logging::verboseMessageHandler);
    
    const char* JURISDICTION_FILE = "--jurisdictionFile";
    const char* jurisdictionFile = getCmdOption(_argc, _argv, JURISDICTION_FILE);
    if (jurisdictionFile) {
        qDebug("jurisdictionFile=%s\n", jurisdictionFile);

        qDebug("about to readFromFile().... jurisdictionFile=%s\n", jurisdictionFile);
        _jurisdiction = new JurisdictionMap(jurisdictionFile);
        qDebug("after readFromFile().... jurisdictionFile=%s\n", jurisdictionFile);
    } else {
        const char* JURISDICTION_ROOT = "--jurisdictionRoot";
        const char* jurisdictionRoot = getCmdOption(_argc, _argv, JURISDICTION_ROOT);
        if (jurisdictionRoot) {
            qDebug("jurisdictionRoot=%s\n", jurisdictionRoot);
        }

        const char* JURISDICTION_ENDNODES = "--jurisdictionEndNodes";
        const char* jurisdictionEndNodes = getCmdOption(_argc, _argv, JURISDICTION_ENDNODES);
        if (jurisdictionEndNodes) {
            qDebug("jurisdictionEndNodes=%s\n", jurisdictionEndNodes);
        }

        if (jurisdictionRoot || jurisdictionEndNodes) {
            _jurisdiction = new JurisdictionMap(jurisdictionRoot, jurisdictionEndNodes);
        }
    }

    // should we send environments? Default is yes, but this command line suppresses sending
    const char* DUMP_VOXELS_ON_MOVE = "--dumpVoxelsOnMove";
    _dumpVoxelsOnMove = cmdOptionExists(_argc, _argv, DUMP_VOXELS_ON_MOVE);
    qDebug("dumpVoxelsOnMove=%s\n", debug::valueOf(_dumpVoxelsOnMove));
    
    // should we send environments? Default is yes, but this command line suppresses sending
    const char* DONT_SEND_ENVIRONMENTS = "--dontSendEnvironments";
    bool dontSendEnvironments =  getCmdOption(_argc, _argv, DONT_SEND_ENVIRONMENTS);
    if (dontSendEnvironments) {
        qDebug("Sending environments suppressed...\n");
        _sendEnvironments = false;
    } else { 
        // should we send environments? Default is yes, but this command line suppresses sending
        const char* MINIMAL_ENVIRONMENT = "--MinimalEnvironment";
        _sendMinimalEnvironment =  getCmdOption(_argc, _argv, MINIMAL_ENVIRONMENT);
        qDebug("Using Minimal Environment=%s\n", debug::valueOf(_sendMinimalEnvironment));
    }
    qDebug("Sending environments=%s\n", debug::valueOf(_sendEnvironments));
    
    NodeList* nodeList = NodeList::getInstance();
    nodeList->setOwnerType(NODE_TYPE_VOXEL_SERVER);
    
    setvbuf(stdout, NULL, _IOLBF, 0);

    // tell our NodeList about our desire to get notifications
    nodeList->addHook(&_nodeWatcher);
    nodeList->linkedDataCreateCallback = &attachVoxelNodeDataToNode;

    nodeList->startSilentNodeRemovalThread();
    srand((unsigned)time(0));
    
    const char* DISPLAY_VOXEL_STATS = "--displayVoxelStats";
    _displayVoxelStats =  getCmdOption(_argc, _argv, DISPLAY_VOXEL_STATS);
    qDebug("displayVoxelStats=%s\n", debug::valueOf(_displayVoxelStats));

    const char* DEBUG_VOXEL_SENDING = "--debugVoxelSending";
    _debugVoxelSending =  getCmdOption(_argc, _argv, DEBUG_VOXEL_SENDING);
    qDebug("debugVoxelSending=%s\n", debug::valueOf(_debugVoxelSending));

    const char* DEBUG_VOXEL_RECEIVING = "--debugVoxelReceiving";
    _debugVoxelReceiving =  getCmdOption(_argc, _argv, DEBUG_VOXEL_RECEIVING);
    qDebug("debugVoxelReceiving=%s\n", debug::valueOf(_debugVoxelReceiving));

    const char* WANT_ANIMATION_DEBUG = "--shouldShowAnimationDebug";
    _shouldShowAnimationDebug =  getCmdOption(_argc, _argv, WANT_ANIMATION_DEBUG);
    qDebug("shouldShowAnimationDebug=%s\n", debug::valueOf(_shouldShowAnimationDebug));

    // By default we will voxel persist, if you want to disable this, then pass in this parameter
    const char* NO_VOXEL_PERSIST = "--NoVoxelPersist";
    if (getCmdOption(_argc, _argv, NO_VOXEL_PERSIST)) {
        _wantVoxelPersist = false;
    }
    qDebug("wantVoxelPersist=%s\n", debug::valueOf(_wantVoxelPersist));

    // if we want Voxel Persistence, load the local file now...
    bool persistantFileRead = false;
    if (_wantVoxelPersist) {

        // Check to see if the user passed in a command line option for setting packet send rate
        const char* VOXELS_PERSIST_FILENAME = "--voxelsPersistFilename";
        const char* voxelsPersistFilenameParameter = getCmdOption(_argc, _argv, VOXELS_PERSIST_FILENAME);
        if (voxelsPersistFilenameParameter) {
            strcpy(_voxelPersistFilename, voxelsPersistFilenameParameter);
        } else {
            //strcpy(voxelPersistFilename, _wantLocalDomain ? LOCAL_VOXELS_PERSIST_FILE : VOXELS_PERSIST_FILE);
            strcpy(_voxelPersistFilename, LOCAL_VOXELS_PERSIST_FILE);
        }

        qDebug("loading voxels from file: %s...\n", _voxelPersistFilename);

        persistantFileRead = _serverTree.readFromSVOFile(_voxelPersistFilename);
        if (persistantFileRead) {
            PerformanceWarning warn(_shouldShowAnimationDebug,
                                    "persistVoxelsWhenDirty() - reaverageVoxelColors()", _shouldShowAnimationDebug);
            
            // after done inserting all these voxels, then reaverage colors
            _serverTree.reaverageVoxelColors(_serverTree.rootNode);
            qDebug("Voxels reAveraged\n");
        }
        
        _serverTree.clearDirtyBit(); // the tree is clean since we just loaded it
        qDebug("DONE loading voxels from file... fileRead=%s\n", debug::valueOf(persistantFileRead));
        unsigned long nodeCount         = _serverTree.rootNode->getSubTreeNodeCount();
        unsigned long internalNodeCount = _serverTree.rootNode->getSubTreeInternalNodeCount();
        unsigned long leafNodeCount     = _serverTree.rootNode->getSubTreeLeafNodeCount();
        qDebug("Nodes after loading scene %lu nodes %lu internal %lu leaves\n", nodeCount, internalNodeCount, leafNodeCount);
        
        // now set up VoxelPersistThread
        _voxelPersistThread = new VoxelPersistThread(&_serverTree, _voxelPersistFilename);
        if (_voxelPersistThread) {
            _voxelPersistThread->initialize(true);
        }
    }

    // Check to see if the user passed in a command line option for loading an old style local
    // Voxel File. If so, load it now. This is not the same as a voxel persist file
    const char* INPUT_FILE = "-i";
    const char* voxelsFilename = getCmdOption(_argc, _argv, INPUT_FILE);
    if (voxelsFilename) {
        _serverTree.readFromSVOFile(voxelsFilename);
    }

    // Check to see if the user passed in a command line option for setting packet send rate
    const char* PACKETS_PER_SECOND = "--packetsPerSecond";
    const char* packetsPerSecond = getCmdOption(_argc, _argv, PACKETS_PER_SECOND);
    if (packetsPerSecond) {
        _packetsPerClientPerInterval = atoi(packetsPerSecond) / INTERVALS_PER_SECOND;
        if (_packetsPerClientPerInterval < 1) {
            _packetsPerClientPerInterval = 1;
        }
        qDebug("packetsPerSecond=%s PACKETS_PER_CLIENT_PER_INTERVAL=%d\n", packetsPerSecond, _packetsPerClientPerInterval);
    }
    
    // for now, initialize the environments with fixed values
    _environmentData[1].setID(1);
    _environmentData[1].setGravity(1.0f);
    _environmentData[1].setAtmosphereCenter(glm::vec3(0.5, 0.5, (0.25 - 0.06125)) * (float)TREE_SCALE);
    _environmentData[1].setAtmosphereInnerRadius(0.030625f * TREE_SCALE);
    _environmentData[1].setAtmosphereOuterRadius(0.030625f * TREE_SCALE * 1.05f);
    _environmentData[2].setID(2);
    _environmentData[2].setGravity(1.0f);
    _environmentData[2].setAtmosphereCenter(glm::vec3(0.5f, 0.5f, 0.5f) * (float)TREE_SCALE);
    _environmentData[2].setAtmosphereInnerRadius(0.1875f * TREE_SCALE);
    _environmentData[2].setAtmosphereOuterRadius(0.1875f * TREE_SCALE * 1.05f);
    _environmentData[2].setScatteringWavelengths(glm::vec3(0.475f, 0.570f, 0.650f)); // swaps red and blue

    sockaddr senderAddress;
    
    unsigned char* packetData = new unsigned char[MAX_PACKET_SIZE];
    ssize_t packetLength;
    
    timeval lastDomainServerCheckIn = {};

    // set up our jurisdiction broadcaster...
    _jurisdictionSender = new JurisdictionSender(_jurisdiction);
    if (_jurisdictionSender) {
        _jurisdictionSender->initialize(true);
    }
    
    // set up our VoxelServerPacketProcessor
    _voxelServerPacketProcessor = new VoxelServerPacketProcessor(this);
    if (_voxelServerPacketProcessor) {
        _voxelServerPacketProcessor->initialize(true);
    }
    
    // loop to send to nodes requesting data
    while (true) {
    
        if (NodeList::getInstance()->getNumNoReplyDomainCheckIns() == MAX_SILENT_DOMAIN_SERVER_CHECK_INS) {
            break;
        }
        
        // send a check in packet to the domain server if DOMAIN_SERVER_CHECK_IN_USECS has elapsed
        if (usecTimestampNow() - usecTimestamp(&lastDomainServerCheckIn) >= DOMAIN_SERVER_CHECK_IN_USECS) {
            gettimeofday(&lastDomainServerCheckIn, NULL);
            NodeList::getInstance()->sendDomainServerCheckIn(_uuid.toRfc4122().constData());
        }
        
        if (nodeList->getNodeSocket()->receive(&senderAddress, packetData, &packetLength) &&
            packetVersionMatch(packetData)) {

            int numBytesPacketHeader = numBytesForPacketHeader(packetData);

            if (packetData[0] == PACKET_TYPE_HEAD_DATA) {
                // If we got a PACKET_TYPE_HEAD_DATA, then we're talking to an NODE_TYPE_AVATAR, and we
                // need to make sure we have it in our nodeList.
                uint16_t nodeID = 0;
                unpackNodeId(packetData + numBytesPacketHeader, &nodeID);
                Node* node = NodeList::getInstance()->addOrUpdateNode(&senderAddress,
                                                       &senderAddress,
                                                       NODE_TYPE_AGENT,
                                                       nodeID);

                NodeList::getInstance()->updateNodeWithData(node, packetData, packetLength);
                
                VoxelNodeData* nodeData = (VoxelNodeData*) node->getLinkedData();
                if (nodeData && !nodeData->isVoxelSendThreadInitalized()) {
                    nodeData->initializeVoxelSendThread(this);
                }
                
            } else if (packetData[0] == PACKET_TYPE_PING) {
                // If the packet is a ping, let processNodeData handle it.
                NodeList::getInstance()->processNodeData(&senderAddress, packetData, packetLength);
            } else if (packetData[0] == PACKET_TYPE_DOMAIN) {
                NodeList::getInstance()->processNodeData(&senderAddress, packetData, packetLength);
            } else if (packetData[0] == PACKET_TYPE_VOXEL_JURISDICTION_REQUEST) {
                if (_jurisdictionSender) {
                    _jurisdictionSender->queueReceivedPacket(senderAddress, packetData, packetLength);
                }
            } else if (_voxelServerPacketProcessor) {
                _voxelServerPacketProcessor->queueReceivedPacket(senderAddress, packetData, packetLength);
            } else {
                qDebug("unknown packet ignored... packetData[0]=%c\n", packetData[0]);
            }
        }
    }
    
    delete _jurisdiction;
    
    if (_jurisdictionSender) {
        _jurisdictionSender->terminate();
        delete _jurisdictionSender;
    }

    if (_voxelServerPacketProcessor) {
        _voxelServerPacketProcessor->terminate();
        delete _voxelServerPacketProcessor;
    }

    if (_voxelPersistThread) {
        _voxelPersistThread->terminate();
        delete _voxelPersistThread;
    }
    
    // tell our NodeList we're done with notifications
    nodeList->removeHook(&_nodeWatcher);
    
    pthread_mutex_destroy(&_treeLock);
}
Beispiel #7
0
/******************************************************************************
 * appMain
 ******************************************************************************/
Int appMain(Args * args)
{

    Buffer_Attrs            bAttrs      = Buffer_Attrs_DEFAULT;
    Loader_Attrs            lAttrs      = Loader_Attrs_DEFAULT;
    SPHDEC1_Params          params      = Sdec1_Params_DEFAULT;
    SPHDEC1_DynamicParams   dynParams   = Sdec1_DynamicParams_DEFAULT;
    Time_Attrs              tAttrs      = Time_Attrs_DEFAULT;
    Sdec1_Handle            hSd1        = NULL;
    Loader_Handle           hLoader     = NULL;
    Engine_Handle           hEngine     = NULL;
    Time_Handle             hTime       = NULL;
    Buffer_Handle           hOutBuf     = NULL;
    Buffer_Handle           hInBuf      = NULL;
    FILE                   *outFile     = NULL;
    Int                     numFrame    = 0;
    UInt32                  time;
    Int                     ret         = Dmai_EOK;

    printf("Starting application...\n");

    if (args->benchmark) {
        hTime = Time_create(&tAttrs);

        if (hTime == NULL) {
            ret = Dmai_EFAIL;
            fprintf(stderr,"Failed to create Time object\n");
            goto cleanup;
        }
    }

    /* Initialize the codec engine run time */
    CERuntime_init();

    /* Initialize DMAI */
    Dmai_init();

    /* Open the output file */
    outFile = fopen(args->outFile, "wb");

    if (outFile == NULL) {
        ret = Dmai_EFAIL;
        fprintf(stderr,"Failed to create output file %s\n", args->outFile);
        goto cleanup;
    }

    /* Using a larger vbuf to enhance performance of file i/o */
    if (setvbuf(outFile, vbuffer, _IOFBF, sizeof(vbuffer)) != 0) {
        ret = Dmai_EFAIL;
        fprintf(stderr,"Failed to setvbuf on file descriptor\n");
        goto cleanup;   
    }
   
    /* Open the codec engine */
    hEngine = Engine_open(args->engineName, NULL, NULL);

    if (hEngine == NULL) {
        ret = Dmai_EFAIL;
        fprintf(stderr,"Failed to open codec engine %s\n", args->engineName);
        goto cleanup;
    }
    
    params.compandingLaw = args->compandingLaw;

    /* Create the SPHDEC1 based speech decoder */
    hSd1 = Sdec1_create(hEngine, args->codecName, &params, &dynParams);

    if (hSd1 == NULL) {
        ret = Dmai_EFAIL;
        fprintf(stderr,"Failed to create %s\n", args->codecName);
        goto cleanup;
    }

    /* Align buffers to cache line boundary */    
    bAttrs.memParams.align = lAttrs.mParams.align = BUFSIZEALIGN; 
    
    /* Use cached buffers if requested */  
    if (args->cache) {
        bAttrs.memParams.flags = lAttrs.mParams.flags = Memory_CACHED;
    } 
    
    /* Ask the codec how much input data it needs */
    lAttrs.readSize = Sdec1_getInBufSize(hSd1);

    /* Make the total ring buffer larger */
    lAttrs.readBufSize = Dmai_roundUp(lAttrs.readSize * 10, BUFSIZEALIGN);

    /* Increase the stdio buffer size for loader for better RTDX performance */
    lAttrs.vBufSize = VBUFSIZE;

    /* Create the file loader */
    hLoader = Loader_create(args->inFile, &lAttrs);

    if (hLoader == NULL) {
        ret = Dmai_EFAIL;
        fprintf(stderr,"Failed to create loader\n");
        goto cleanup;
    }

    /* Create an output buffer for decoded data */
    hOutBuf = Buffer_create(
        Dmai_roundUp(Sdec1_getOutBufSize(hSd1), BUFSIZEALIGN), &bAttrs);

    if (hOutBuf == NULL) {
        ret = Dmai_EFAIL;
        fprintf(stderr,"Failed to create contiguous buffers\n");
        goto cleanup;
    }

    /* Prime the file loader */
    Loader_prime(hLoader, &hInBuf);

    while (numFrame++ < args->numFrames) {
        if (args->benchmark) {
            if (Time_reset(hTime) < 0) {
                ret = Dmai_EFAIL;
                fprintf(stderr,"Failed to reset timer\n");
                goto cleanup;
            }
        }

        if (args->cache) {
            /*  
             *  To meet xDAIS DMA Rule 7, when input buffers are cached, we 
             *  must writeback the cache into physical memory.  Also, per DMA 
             *  Rule 7, we must invalidate the output buffer from
             *  cache before providing it to any xDAIS algorithm.
             */
            Memory_cacheWbInv(Buffer_getUserPtr(hInBuf),Buffer_getSize(hInBuf));
    
            /* Per DMA Rule 7, our output buffer cache lines must be cleaned */
            Memory_cacheInv(Buffer_getUserPtr(hOutBuf),Buffer_getSize(hOutBuf));
            
            if (args->benchmark) {
                if (Time_delta(hTime, &time) < 0) {
                    ret = Dmai_EFAIL;
                    fprintf(stderr,"Failed to get timer delta\n");
                    goto cleanup;
                }
    
                printf("Pre-process cache maintenance: %uus ", (Uns) time);
            }
        }
        
        /* Decode the speech buffer */
        if (Sdec1_process(hSd1, hInBuf, hOutBuf) < 0) {
            ret = Dmai_EFAIL;
            fprintf(stderr,"Failed to decode speech buffer\n");
            goto cleanup;
        }

         if (args->benchmark) {
            if (Time_delta(hTime, &time) < 0) {
                ret = Dmai_EFAIL;
                fprintf(stderr,"Failed to get timer delta\n");
                goto cleanup;
            }

            printf("Decode: %uus ", (Uns) time);
        }
        
        if (args->cache) {
            /* Writeback the outBuf. */
            Memory_cacheWb(Buffer_getUserPtr(hOutBuf), Buffer_getSize(hOutBuf));
    
            if (args->benchmark) {
                if (Time_delta(hTime, &time) < 0) {
                    ret = Dmai_EFAIL;
                    fprintf(stderr,"Failed to get timer delta\n");
                    goto cleanup;
                }
    
                printf("Post-process cache write back: %uus ", (Uns) time);
            }
        }
         
        /* Load a new frame from the file system */
        Loader_getFrame(hLoader, hInBuf);

        if (args->benchmark) {
            if (Time_delta(hTime, &time) < 0) {
                ret = Dmai_EFAIL;
                fprintf(stderr,"Failed to get timer delta\n");
                goto cleanup;
            }

            printf("Loader: %uus\n", (Uns) time);
        }

        if (Buffer_getNumBytesUsed(hOutBuf)) {
            if (numFrame >= args->startFrame) {
                printf("Frame %d: ", numFrame);
                if (writeFrame(hOutBuf, outFile) < 0) {
                    ret = Dmai_EFAIL;
                    goto cleanup;
                }
            }
        }

        if (Buffer_getUserPtr(hInBuf) == NULL) {
            ret = Dmai_EFAIL;
            fprintf(stderr,"Loader returned null, clip finished\n");
            break;
        }

        if (args->benchmark) {
            if (Time_total(hTime, &time) < 0) {
                ret = Dmai_EFAIL;
                fprintf(stderr,"Failed to get timer total\n");
                goto cleanup;
            }

            printf("Total: %uus\n", (unsigned int)time);
        }
    }

cleanup:
    /* Clean up the application */
    if (hLoader) {
        Loader_delete(hLoader);
    }

    if (hSd1) {
        Sdec1_delete(hSd1);
    }

    if (hOutBuf) {
        Buffer_delete(hOutBuf);
    }

    if (hEngine) {
        Engine_close(hEngine);
    }

    if (hTime) {
        Time_delete(hTime);
    }

    if (outFile) {
        fclose(outFile);
    }
    
    printf("End of application.\n");

    if (ret == Dmai_EFAIL)
        return 1;
    else
        return 0;
}
Beispiel #8
0
void setbuffer(FILE *stream, char *buf, size_t size) {
    setvbuf(stream, buf, buf ? _IOFBF : _IONBF, size);
}
Beispiel #9
0
int main(int argc, char** argv)
{
    // nspluginviewer is a helper app, it shouldn't do session management at all
   setenv( "SESSION_MANAGER", "", 1 );

   // trap X errors
   kdDebug(1430) << "1 - XSetErrorHandler" << endl;
   XSetErrorHandler(x_errhandler);
   setvbuf( stderr, NULL, _IONBF, 0 );

   kdDebug(1430) << "2 - parseCommandLine" << endl;
   parseCommandLine(argc, argv);

   kdDebug(1430) << "3 - create QXtEventLoop" << endl;
   QXtEventLoop integrator( "nspluginviewer" );
   parseCommandLine(argc, argv);
   TDELocale::setMainCatalogue("nsplugin");

   kdDebug(1430) << "4 - create TDEApplication" << endl;
   TDEApplication app( argc,  argv, "nspluginviewer", true, true, true );
   GlibEvents glibevents;

   {
      TDEConfig cfg("kcmnspluginrc", true);
      cfg.setGroup("Misc");
      int v = KCLAMP(cfg.readNumEntry("Nice Level", 0), 0, 19);
      if (v > 0) {
         nice(v);
      }
      v = cfg.readNumEntry("Max Memory", 0);
      if (v > 0) {
         rlimit rl;
         memset(&rl, 0, sizeof(rl));
         if (0 == getrlimit(RLIMIT_AS, &rl)) {
            rl.rlim_cur = kMin(v, int(rl.rlim_max));
            setrlimit(RLIMIT_AS, &rl);
         }
      }
   }

   // initialize the dcop client
   kdDebug(1430) << "5 - app.dcopClient" << endl;
   DCOPClient *dcop = app.dcopClient();
   if (!dcop->attach())
   {
      KMessageBox::error(NULL,
                            i18n("There was an error connecting to the Desktop "
                                 "communications server. Please make sure that "
                                 "the 'dcopserver' process has been started, and "
                                 "then try again."),
                            i18n("Error Connecting to DCOP Server"));
      exit(1);
   }

   kdDebug(1430) << "6 - dcop->registerAs" << endl;
   if (g_dcopId != 0)
      g_dcopId = dcop->registerAs( g_dcopId, false );
   else
      g_dcopId = dcop->registerAs("nspluginviewer");

   dcop->setNotifications(true);

   // create dcop interface
   kdDebug(1430) << "7 - new NSPluginViewer" << endl;
   NSPluginViewer *viewer = new NSPluginViewer( "viewer", 0 );

   // start main loop
#if TQT_VERSION < 0x030100
   kdDebug(1430) << "8 - XtAppProcessEvent" << endl;
   while (!g_quit)
     XtAppProcessEvent( g_appcon, XtIMAll);
#else
   kdDebug(1430) << "8 - app.exec()" << endl;
   app.exec();
#endif

   // delete viewer
   delete viewer;
}
Beispiel #10
0
int main() 
{
    static const unsigned int testFileSize = 1 * 1024 * 1024;
    static SDFileSystem       sdFatFileSystem(p5, p6, p7, p8, "sd");
    static Timer              timer;
    FILE*                     pFile = NULL;
    size_t                    bytesTransferred = 0;
    size_t                    i = 0;
    int                       seekResult = -1;
    char                      filenameBuffer[256];
    static __attribute((section("AHBSRAM0"),aligned)) unsigned char buffer[16 * 1024];
    static __attribute((section("AHBSRAM1"),aligned)) char          cache[16 * 1024];
    

    // Search for a unique filename to test with.
    for (i = 0 ; ; i++)
    {
        snprintf(filenameBuffer, sizeof(filenameBuffer), "/sd/tst%u.bin", i);
        printf("Trying %s...", filenameBuffer);
        pFile = fopen(filenameBuffer, "r");
        if (!pFile)
        {
            printf("free!\n");
            break;
        }
        printf("exists!\n");
        fclose(pFile);
    }
    
    printf("Performing write test...\n");
    memset(buffer, 0x55, sizeof(buffer));
    
    // Write out large file to SD card and time the write.
    pFile = fopen(filenameBuffer, "w");
    if (!pFile)
    {
        printf("error: Failed to create %s", filenameBuffer);
        perror(NULL);
        exit(-1);
    }
    setvbuf(pFile, cache, _IOFBF, sizeof(cache));

    timer.start();
    for (i = 0 ; i < testFileSize / sizeof(buffer) ; i++)
    {
        bytesTransferred = fwrite(buffer, 1, sizeof(buffer), pFile);
        if (bytesTransferred != sizeof(buffer))
        {
            printf("error: Failed to write to %s", filenameBuffer);
            perror(NULL);
            exit(-1);
        }
    }
    unsigned int totalTicks = (unsigned int)timer.read_ms();
    unsigned int totalBytes = ftell(pFile);
    fclose(pFile);

    printf("Wrote %u bytes in %u milliseconds.\n", totalBytes, totalTicks);
    printf("%f bytes/second.\n", totalBytes / (totalTicks / 1000.0f));
    printf("%f MB/second.\n", (totalBytes / (totalTicks / 1000.0f)) / (1024.0f * 1024.0f));


    printf("Performing read test...\n");
    pFile = fopen(filenameBuffer, "r");
    if (!pFile)
    {
        printf("error: Failed to open %s", filenameBuffer);
        perror(NULL);
        exit(-1);
    }
    setvbuf(pFile, cache, _IOFBF, sizeof(cache));
    
    timer.reset();
    for (;;)
    {
        bytesTransferred = fread(buffer, 1, sizeof(buffer), pFile);
        if (bytesTransferred != sizeof(buffer))
        {
            if (ferror(pFile))
            {
                printf("error: Failed to read from %s", filenameBuffer);
                perror(NULL);
                exit(-1);
            }
            else
            {
                break;
            }
        }
    }
    totalTicks = (unsigned int)timer.read_ms();
    totalBytes = ftell(pFile);

    printf("Read %u bytes in %u milliseconds.\n", totalBytes, totalTicks);
    printf("%f bytes/second.\n", totalBytes / (totalTicks / 1000.0f));
    printf("%f MB/second.\n", (totalBytes / (totalTicks / 1000.0f)) / (1024.0f * 1024.0f));
    
    
    printf("Validating data read.  Not for performance measurement.\n");
    seekResult = fseek(pFile, 0, SEEK_SET);
    if (seekResult)
    {
        perror("error: Failed to seek to beginning of file");
        exit(-1);
    }
    
    for (;;)
    {
        unsigned int   j;
        unsigned char* pCurr;
        
        memset(buffer, 0xaa, sizeof(buffer));
        bytesTransferred = fread(buffer, 1, sizeof(buffer), pFile);
        if (bytesTransferred != sizeof(buffer) && ferror(pFile))
        {
            printf("error: Failed to read from %s", filenameBuffer);
            perror(NULL);
            exit(-1);
        }
        
        for (j = 0, pCurr = buffer ; j < bytesTransferred ; j++)
        {
            if (*pCurr++ != 0x55)
            {
                printf("error: Unexpected read byte encountered.");
                exit(-1);
            }
        }
        
        if (bytesTransferred != sizeof(buffer))
            break;
    }
    totalBytes = ftell(pFile);
    printf("Validated %u bytes.\n", totalBytes);
    fclose(pFile);

    printf("Determine size of file through fseek and ftell calls.\n");
    pFile = fopen(filenameBuffer, "r");
    seekResult = fseek(pFile, 0, SEEK_END);
    long size = ftell(pFile);
    if ((long)testFileSize != size)
    {
        printf("error: ftell returned %ld instead of the expected value of %u.\n", size, testFileSize);
        exit(-1);
    }
    fclose(pFile);
    
    printf("Create directories.\n");
    remove("/sd/testdir1/z");
    remove("/sd/testdir1/a");
    remove("/sd/testdir1");
    int mkdirResult = mkdir("/sd/testdir1", 0);
    if (mkdirResult)
    {
        perror("error: mkdir(/sd/testdir1) failed");
        exit(-1);
    }
    mkdirResult = mkdir("/sd/testdir1/a", 0);
    if (mkdirResult)
    {
        perror("error: mkdir(/sd/testdir1/a) failed");
        exit(-1);
    }
    mkdirResult = mkdir("/sd/testdir1/z", 0);
    if (mkdirResult)
    {
        perror("error: mkdir(/sd/testdir1/z) failed");
        exit(-1);
    }

    // Enumerate all content on mounted file systems.
    printf("\nList all files in /sd...\n");
    _RecursiveDir("/sd");

    printf("Cleanup test directories.\n");
    int removeResult = remove("/sd/testdir1/z");
    if (removeResult)
    {
        perror("error: remove(sd/testdir1/z) failed");
        exit(-1);
    }
    removeResult = remove("/sd/testdir1/a");
    if (removeResult)
    {
        perror("error: remove(sd/testdir1/a) failed");
        exit(-1);
    }
    removeResult = remove("/sd/testdir1");
    if (removeResult)
    {
        perror("error: remove(sd/testdir1) failed");
        exit(-1);
    }
    
    printf("Remove test file.\n");
    removeResult = remove(filenameBuffer);
    if (removeResult)
    {
        perror("error: remove() failed");
        exit(-1);
    }

    return 0;
}
Beispiel #11
0
int main(int argc,char *argv[]){
	const char *servname = "foo.sock";
	struct sockaddr_un serv;	
	int size,ret,master_socket,cld,maxfd=0,i;
	//初始化为零
	int clients[MAX_CLIENT_NUM];
	char buf[1024];
	int opt=1;
	fd_set rdfs;
	socklen_t len;		
	/**********/
	//设置标准输出流为无缓冲
	setvbuf(stdout,NULL,_IONBF,0);

	for(i=0;i<MAX_CLIENT_NUM;i++){
		clients[i]=0;
	}

	if((master_socket=socket(AF_UNIX,SOCK_STREAM,0))<0){
		perror("socket error:\n");
		goto fail;
	}
	/*********/
	 if( setsockopt(master_socket, SOL_SOCKET, SO_REUSEADDR, (char *)&opt, sizeof(opt)) < 0 )
     {
        perror("setsockopt");
		goto fail;
     }

	/**********/
	memset(&serv,0,sizeof(struct sockaddr_un));
	serv.sun_family = AF_UNIX;
	strcpy(serv.sun_path,servname);
	len=offsetof(struct sockaddr_un,sun_path)+strlen(servname)+1;
	if((ret=bind(master_socket,(struct sockaddr*)&serv,len))<0){
		perror("bind error:\n");
		goto fail;
	}
	/*********/

	/********/
	if((ret=listen(master_socket,MAX_CONN_NUM))<0){
		perror("listen error:\n");
		goto fail;
	}
	/********/
	struct timeval tv;
	//主循环
	while(1){
		//每次要重新设置fdset!!!
		FD_ZERO(&rdfs);
		FD_SET(master_socket,&rdfs);
		maxfd=master_socket;
		for(i=0;i<MAX_CLIENT_NUM;i++){
			if(clients[i]==0)
				continue;
			FD_SET(clients[i],&rdfs);
			if(clients[i]>maxfd)
				maxfd=clients[i];
		}
		tv.tv_sec=5;
		tv.tv_usec=0;
		ret=select(maxfd+1,&rdfs,NULL,NULL,&tv);
		if(ret<0){
			perror("select error\n");
			goto fail;
		}
		else if(ret==0){
			printf("no data availabe\n");
		}
		else{
			if(FD_ISSET(master_socket,&rdfs)){
				//master_socket有数据来了,说明有新的链接到达
				printf("a new connection comes\n");
				if((cld=accept(master_socket,NULL,NULL))<0){
					perror("accept error\n");
					goto fail;
				}
				for(i=0;i<MAX_CLIENT_NUM;i++){
					if(clients[i]==0){
						clients[i]=cld;
						if(cld>maxfd)
							maxfd=cld;
						FD_SET(cld,&rdfs);
						break;
					}
				}
				//说明超过最大连接个数,不接受,关闭cld
				if(i==MAX_CLIENT_NUM){
					printf("exceeding the max conn num,do not accept it\n");
					close(cld);
				}
			}
			//处理客户端传来的数据
			for(i=0;i<MAX_CLIENT_NUM;i++){
				if(clients[i]==0)
					continue;
				//该cld有数据到达
				if(FD_ISSET(clients[i],&rdfs)){
					//这里的设置是关健:1.处理断开连接的情况2.设置成nonblock
					while((size=recv(clients[i],buf,1024,MSG_DONTWAIT))>0){
						struct mymsghdr *msg=(struct mymsghdr *)buf;
						//注意这里printf是行缓冲的,所以不会打印出来,不要将标准I/O流和read,write弄混了
						printf("message from %5d:",msg->pid);
						write(1,msg->data,msg->len);
					}
					if(size<0){
						if(errno==EAGAIN || errno==EWOULDBLOCK){
							continue;
						}
						else{
							perror("read error\n");
							goto fail;
						}
					}
					//处理断开连接的情况
					if(size==0){
						printf("a connection closed\n");
						clients[i]=0;
					}
				}
			}
		}
	}


	fail:
		for(i=0;i<MAX_CLIENT_NUM;i++){
			if(clients[i])
				close(clients[i]);
		}
		close(master_socket);
		return -1;
}
int rom_installer_main(int argc, char *argv[])
{
    if (unshare(CLONE_NEWNS) < 0) {
        fprintf(stderr, "unshare() failed: %s\n", strerror(errno));
        return EXIT_FAILURE;
    }

    if (mount("", "/", "", MS_PRIVATE | MS_REC, "") < 0) {
        fprintf(stderr, "Failed to set private mount propagation: %s\n",
                strerror(errno));
        return false;
    }

    // Make stdout unbuffered
    setvbuf(stdout, nullptr, _IONBF, 0);

    std::string rom_id;
    std::string zip_file;

    int opt;

    static struct option long_options[] = {
        {"romid", required_argument, 0, 'r'},
        {"help",  no_argument,       0, 'h'},
        {0, 0, 0, 0}
    };

    int long_index = 0;

    while ((opt = getopt_long(argc, argv, "r:h", long_options, &long_index)) != -1) {
        switch (opt) {
        case 'r':
            rom_id = optarg;
            break;

        case 'h':
            rom_installer_usage(false);
            return EXIT_SUCCESS;

        default:
            rom_installer_usage(true);
            return EXIT_FAILURE;
        }
    }

    if (argc - optind != 1) {
        rom_installer_usage(true);
        return EXIT_FAILURE;
    }

    zip_file = argv[optind];

    if (rom_id.empty()) {
        fprintf(stderr, "-r/--romid must be specified\n");
        return EXIT_FAILURE;
    }

    if (zip_file.empty()) {
        fprintf(stderr, "Invalid zip file path\n");
        return EXIT_FAILURE;
    }


    // Make sure install type is valid
    if (!Roms::is_valid(rom_id)) {
        fprintf(stderr, "Invalid ROM ID: %s\n", rom_id.c_str());
        return EXIT_FAILURE;
    }

    auto rom = Roms::get_current_rom();
    if (!rom) {
        fprintf(stderr, "Could not determine current ROM\n");
        return EXIT_FAILURE;
    }

    if (rom->id == rom_id) {
        fprintf(stderr, "Can't install over current ROM (%s)\n",
                rom_id.c_str());
        return EXIT_FAILURE;
    }


    if (geteuid() != 0) {
        fprintf(stderr, "rom-installer must be run as root\n");
        return EXIT_FAILURE;
    }

    if (mount("", "/", "", MS_REMOUNT, "") < 0) {
        fprintf(stderr, "Failed to remount / as writable\n");
        return EXIT_FAILURE;
    }


    // We do not need to patch the SELinux policy or switch to mb_exec because
    // the daemon will guarantee that we run in that context. We'll just warn if
    // this happens to not be the case (eg. debugging via command line).

    std::string context;
    if (util::selinux_get_process_attr(
            0, util::SELinuxAttr::CURRENT, &context)
            && context != MB_EXEC_CONTEXT) {
        fprintf(stderr, "WARNING: Not running under %s context\n",
                MB_EXEC_CONTEXT);
    }


    autoclose::file fp(autoclose::fopen(MULTIBOOT_LOG_INSTALLER, "wb"));
    if (!fp) {
        fprintf(stderr, "Failed to open %s: %s\n",
                MULTIBOOT_LOG_INSTALLER, strerror(errno));
        return EXIT_FAILURE;
    }

    fix_multiboot_permissions();

    // Close stdin
#if !DEBUG_LEAVE_STDIN_OPEN
    int fd = open("/dev/null", O_RDONLY);
    if (fd >= 0) {
        dup2(fd, STDIN_FILENO);
        close(fd);
    }
#endif

    // mbtool logging
    log::log_set_logger(std::make_shared<log::StdioLogger>(fp.get(), false));

    // Start installing!
    RomInstaller ri(zip_file, rom_id, fp.get());
    return ri.start_installation() ? EXIT_SUCCESS : EXIT_FAILURE;
}
int
main(int argc, char *argv[])
{
	int sk1, sk2;
	sockaddr_storage_t loop1, loop2;
	struct msghdr inmessage, outmessage;
	struct iovec iov, out_iov;
	int error;
	char *big_buffer;
	char *message = "hello, world!\n";
	uint32_t autoclose;

	/* Rather than fflush() throughout the code, set stdout to 
	 * be unbuffered. 
	 */
	setvbuf(stdout, NULL, _IONBF, 0); 

	loop1.v4.sin_family = AF_INET;
	loop1.v4.sin_addr.s_addr = SCTP_IP_LOOPBACK;
	loop1.v4.sin_port = htons(SCTP_TESTPORT_1);

	loop2.v4.sin_family = AF_INET;
	loop2.v4.sin_addr.s_addr = SCTP_IP_LOOPBACK;
	loop2.v4.sin_port = htons(SCTP_TESTPORT_2);

	/* Create the two endpoints which will talk to each other.  */
	sk1 = test_socket(AF_INET, SOCK_SEQPACKET, IPPROTO_SCTP);
	sk2 = test_socket(AF_INET, SOCK_SEQPACKET, IPPROTO_SCTP);

	/* Enable ASSOC_CHANGE and SNDRCVINFO notifications. */
	test_enable_assoc_change(sk1);
	test_enable_assoc_change(sk2);

	/* Bind these sockets to the test ports.  */
	test_bind(sk1, &loop1.sa, sizeof(loop1));
	test_bind(sk2, &loop2.sa, sizeof(loop2));

	/* Mark sk2 as being able to accept new associations.  */
	test_listen(sk2, 1);

	/* Set the autoclose duration for the associations created on sk1 
	 * and sk2 to be 5 seconds.  
	 */ 
	autoclose = 5;
	test_setsockopt(sk1, SCTP_AUTOCLOSE, &autoclose, sizeof(autoclose));
	test_setsockopt(sk2, SCTP_AUTOCLOSE, &autoclose, sizeof(autoclose));

	/* Send the first message.  This will create the association.  */
	memset(&outmessage, 0, sizeof(outmessage));	
	outmessage.msg_name = &loop2;
	outmessage.msg_namelen = sizeof(loop2);
	outmessage.msg_iov = &out_iov;
	outmessage.msg_iovlen = 1;
	outmessage.msg_iov->iov_base = message;
	outmessage.msg_iov->iov_len = strlen(message) + 1;

	test_sendmsg(sk1, &outmessage, 0, strlen(message)+1);

	/* Initialize inmessage for all receives. */
	big_buffer = test_malloc(REALLY_BIG);
        memset(&inmessage, 0, sizeof(inmessage));	
	iov.iov_base = big_buffer;
	iov.iov_len = REALLY_BIG;
	inmessage.msg_iov = &iov;
	inmessage.msg_iovlen = 1;
	inmessage.msg_control = NULL;

	/* Get the communication up message on sk2.  */
	error = test_recvmsg(sk2, &inmessage, MSG_WAITALL);
	test_check_msg_notification(&inmessage, error,
				    sizeof(struct sctp_assoc_change),
				    SCTP_ASSOC_CHANGE, SCTP_COMM_UP);	

	/* Get the communication up message on sk1.  */
	error = test_recvmsg(sk1, &inmessage, MSG_WAITALL);
	test_check_msg_notification(&inmessage, error,
				    sizeof(struct sctp_assoc_change),
				    SCTP_ASSOC_CHANGE, SCTP_COMM_UP);	

	/* Get the first message which was sent.  */
	error = test_recvmsg(sk2, &inmessage, MSG_WAITALL);
	test_check_msg_data(&inmessage, error, strlen(message) + 1,
			    MSG_EOR|MSG_CTRUNC, 0, 0);

	tst_resm(TINFO, "Waiting for the associations to close automatically "
		 "in 5 secs");

	/* Get the shutdown complete notification from sk1. */
	error = test_recvmsg(sk1, &inmessage, MSG_WAITALL);
	test_check_msg_notification(&inmessage, error,
				    sizeof(struct sctp_assoc_change),
				    SCTP_ASSOC_CHANGE, SCTP_SHUTDOWN_COMP);	
				
	/* Get the shutdown complete notification from sk2. */
	error = test_recvmsg(sk2, &inmessage, MSG_WAITALL);
	test_check_msg_notification(&inmessage, error,
				    sizeof(struct sctp_assoc_change),
				    SCTP_ASSOC_CHANGE, SCTP_SHUTDOWN_COMP);	

	tst_resm(TPASS, "Autoclose of associations");

	/* Shut down the link.  */
	close(sk1);
	close(sk2);

	/* Indicate successful completion.  */
	return 0;
}
int MAIN(int argc, char **argv)
	{
#ifndef OPENSSL_NO_ENGINE
	ENGINE *e = NULL;
#endif
	static const char magic[]="Salted__";
	char mbuf[sizeof magic-1];
	char *strbuf=NULL;
	unsigned char *buff=NULL,*bufsize=NULL;
	int bsize=BSIZE,verbose=0;
	int ret=1,inl;
	int nopad = 0;
	unsigned char key[EVP_MAX_KEY_LENGTH],iv[EVP_MAX_IV_LENGTH];
	unsigned char salt[PKCS5_SALT_LEN];
	char *str=NULL, *passarg = NULL, *pass = NULL;
	char *hkey=NULL,*hiv=NULL,*hsalt = NULL;
	char *md=NULL;
	int enc=1,printkey=0,i,base64=0;
	int debug=0,olb64=0,nosalt=0;
	const EVP_CIPHER *cipher=NULL,*c;
	EVP_CIPHER_CTX *ctx = NULL;
	char *inf=NULL,*outf=NULL;
	BIO *in=NULL,*out=NULL,*b64=NULL,*benc=NULL,*rbio=NULL,*wbio=NULL;
#define PROG_NAME_SIZE  39
	char pname[PROG_NAME_SIZE+1];
#ifndef OPENSSL_NO_ENGINE
	char *engine = NULL;
#endif
	const EVP_MD *dgst=NULL;
	int non_fips_allow = 0;

	apps_startup();

	if (bio_err == NULL)
		if ((bio_err=BIO_new(BIO_s_file())) != NULL)
			BIO_set_fp(bio_err,stderr,BIO_NOCLOSE|BIO_FP_TEXT);

	if (!load_config(bio_err, NULL))
		goto end;

	/* first check the program name */
	program_name(argv[0],pname,sizeof pname);
	if (strcmp(pname,"base64") == 0)
		base64=1;

	cipher=EVP_get_cipherbyname(pname);
	if (!base64 && (cipher == NULL) && (strcmp(pname,"enc") != 0))
		{
		BIO_printf(bio_err,"%s is an unknown cipher\n",pname);
		goto bad;
		}

	argc--;
	argv++;
	while (argc >= 1)
		{
		if	(strcmp(*argv,"-e") == 0)
			enc=1;
		else if (strcmp(*argv,"-in") == 0)
			{
			if (--argc < 1) goto bad;
			inf= *(++argv);
			}
		else if (strcmp(*argv,"-out") == 0)
			{
			if (--argc < 1) goto bad;
			outf= *(++argv);
			}
		else if (strcmp(*argv,"-pass") == 0)
			{
			if (--argc < 1) goto bad;
			passarg= *(++argv);
			}
#ifndef OPENSSL_NO_ENGINE
		else if (strcmp(*argv,"-engine") == 0)
			{
			if (--argc < 1) goto bad;
			engine= *(++argv);
			}
#endif
		else if	(strcmp(*argv,"-d") == 0)
			enc=0;
		else if	(strcmp(*argv,"-p") == 0)
			printkey=1;
		else if	(strcmp(*argv,"-v") == 0)
			verbose=1;
		else if	(strcmp(*argv,"-nopad") == 0)
			nopad=1;
		else if	(strcmp(*argv,"-salt") == 0)
			nosalt=0;
		else if	(strcmp(*argv,"-nosalt") == 0)
			nosalt=1;
		else if	(strcmp(*argv,"-debug") == 0)
			debug=1;
		else if	(strcmp(*argv,"-P") == 0)
			printkey=2;
		else if	(strcmp(*argv,"-A") == 0)
			olb64=1;
		else if	(strcmp(*argv,"-a") == 0)
			base64=1;
		else if	(strcmp(*argv,"-base64") == 0)
			base64=1;
		else if (strcmp(*argv,"-bufsize") == 0)
			{
			if (--argc < 1) goto bad;
			bufsize=(unsigned char *)*(++argv);
			}
		else if (strcmp(*argv,"-k") == 0)
			{
			if (--argc < 1) goto bad;
			str= *(++argv);
			}
		else if (strcmp(*argv,"-kfile") == 0)
			{
			static char buf[128];
			FILE *infile;
			char *file;

			if (--argc < 1) goto bad;
			file= *(++argv);
			infile=fopen(file,"r");
			if (infile == NULL)
				{
				BIO_printf(bio_err,"unable to read key from '%s'\n",
					file);
				goto bad;
				}
			buf[0]='\0';
			fgets(buf,sizeof buf,infile);
			fclose(infile);
			i=strlen(buf);
			if ((i > 0) &&
				((buf[i-1] == '\n') || (buf[i-1] == '\r')))
				buf[--i]='\0';
			if ((i > 0) &&
				((buf[i-1] == '\n') || (buf[i-1] == '\r')))
				buf[--i]='\0';
			if (i < 1)
				{
				BIO_printf(bio_err,"zero length password\n");
				goto bad;
				}
			str=buf;
			}
		else if (strcmp(*argv,"-K") == 0)
			{
			if (--argc < 1) goto bad;
			hkey= *(++argv);
			}
		else if (strcmp(*argv,"-S") == 0)
			{
			if (--argc < 1) goto bad;
			hsalt= *(++argv);
			}
		else if (strcmp(*argv,"-iv") == 0)
			{
			if (--argc < 1) goto bad;
			hiv= *(++argv);
			}
		else if (strcmp(*argv,"-md") == 0)
			{
			if (--argc < 1) goto bad;
			md= *(++argv);
			}
		else if (strcmp(*argv,"-non-fips-allow") == 0)
			non_fips_allow = 1;
		else if	((argv[0][0] == '-') &&
			((c=EVP_get_cipherbyname(&(argv[0][1]))) != NULL))
			{
			cipher=c;
			}
		else if (strcmp(*argv,"-none") == 0)
			cipher=NULL;
		else
			{
			BIO_printf(bio_err,"unknown option '%s'\n",*argv);
bad:
			BIO_printf(bio_err,"options are\n");
			BIO_printf(bio_err,"%-14s input file\n","-in <file>");
			BIO_printf(bio_err,"%-14s output file\n","-out <file>");
			BIO_printf(bio_err,"%-14s pass phrase source\n","-pass <arg>");
			BIO_printf(bio_err,"%-14s encrypt\n","-e");
			BIO_printf(bio_err,"%-14s decrypt\n","-d");
			BIO_printf(bio_err,"%-14s base64 encode/decode, depending on encryption flag\n","-a/-base64");
			BIO_printf(bio_err,"%-14s passphrase is the next argument\n","-k");
			BIO_printf(bio_err,"%-14s passphrase is the first line of the file argument\n","-kfile");
			BIO_printf(bio_err,"%-14s the next argument is the md to use to create a key\n","-md");
			BIO_printf(bio_err,"%-14s   from a passphrase.  One of md2, md5, sha or sha1\n","");
			BIO_printf(bio_err,"%-14s key/iv in hex is the next argument\n","-K/-iv");
			BIO_printf(bio_err,"%-14s print the iv/key (then exit if -P)\n","-[pP]");
			BIO_printf(bio_err,"%-14s buffer size\n","-bufsize <n>");
#ifndef OPENSSL_NO_ENGINE
			BIO_printf(bio_err,"%-14s use engine e, possibly a hardware device.\n","-engine e");
#endif

			BIO_printf(bio_err,"Cipher Types\n");
			OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_CIPHER_METH,
					       show_ciphers,
					       bio_err);
			BIO_printf(bio_err,"\n");

			goto end;
			}
		argc--;
		argv++;
		}

#ifndef OPENSSL_NO_ENGINE
        e = setup_engine(bio_err, engine, 0);
#endif

	if (md && (dgst=EVP_get_digestbyname(md)) == NULL)
		{
		BIO_printf(bio_err,"%s is an unsupported message digest type\n",md);
		goto end;
		}

	if (dgst == NULL)
		{
		if (in_FIPS_mode)
			dgst = EVP_sha1();
		else
			dgst = EVP_md5();
		}

	if (bufsize != NULL)
		{
		unsigned long n;

		for (n=0; *bufsize; bufsize++)
			{
			i= *bufsize;
			if ((i <= '9') && (i >= '0'))
				n=n*10+i-'0';
			else if (i == 'k')
				{
				n*=1024;
				bufsize++;
				break;
				}
			}
		if (*bufsize != '\0')
			{
			BIO_printf(bio_err,"invalid 'bufsize' specified.\n");
			goto end;
			}

		/* It must be large enough for a base64 encoded line */
		if (base64 && n < 80) n=80;

		bsize=(int)n;
		if (verbose) BIO_printf(bio_err,"bufsize=%d\n",bsize);
		}

	strbuf=OPENSSL_malloc(SIZE);
	buff=(unsigned char *)OPENSSL_malloc(EVP_ENCODE_LENGTH(bsize));
	if ((buff == NULL) || (strbuf == NULL))
		{
		BIO_printf(bio_err,"OPENSSL_malloc failure %ld\n",(long)EVP_ENCODE_LENGTH(bsize));
		goto end;
		}

	in=BIO_new(BIO_s_file());
	out=BIO_new(BIO_s_file());
	if ((in == NULL) || (out == NULL))
		{
		ERR_print_errors(bio_err);
		goto end;
		}
	if (debug)
		{
		BIO_set_callback(in,BIO_debug_callback);
		BIO_set_callback(out,BIO_debug_callback);
		BIO_set_callback_arg(in,(char *)bio_err);
		BIO_set_callback_arg(out,(char *)bio_err);
		}

	if (inf == NULL)
	        {
		if (bufsize != NULL)
			setvbuf(stdin, (char *)NULL, _IONBF, 0);
		BIO_set_fp(in,stdin,BIO_NOCLOSE);
	        }
	else
		{
		if (BIO_read_filename(in,inf) <= 0)
			{
			perror(inf);
			goto end;
			}
		}

	if(!str && passarg) {
		if(!app_passwd(bio_err, passarg, NULL, &pass, NULL)) {
			BIO_printf(bio_err, "Error getting password\n");
			goto end;
		}
		str = pass;
	}

	if ((str == NULL) && (cipher != NULL) && (hkey == NULL))
		{
		for (;;)
			{
			char buf[200];

			BIO_snprintf(buf,sizeof buf,"enter %s %s password:"******"encryption":"decryption");
			strbuf[0]='\0';
			i=EVP_read_pw_string((char *)strbuf,SIZE,buf,enc);
			if (i == 0)
				{
				if (strbuf[0] == '\0')
					{
					ret=1;
					goto end;
					}
				str=strbuf;
				break;
				}
			if (i < 0)
				{
				BIO_printf(bio_err,"bad password read\n");
				goto end;
				}
			}
		}


	if (outf == NULL)
		{
		BIO_set_fp(out,stdout,BIO_NOCLOSE);
		if (bufsize != NULL)
			setvbuf(stdout, (char *)NULL, _IONBF, 0);
#ifdef OPENSSL_SYS_VMS
		{
		BIO *tmpbio = BIO_new(BIO_f_linebuffer());
		out = BIO_push(tmpbio, out);
		}
#endif
		}
	else
		{
		if (BIO_write_filename(out,outf) <= 0)
			{
			perror(outf);
			goto end;
			}
		}

	rbio=in;
	wbio=out;

	if (base64)
		{
		if ((b64=BIO_new(BIO_f_base64())) == NULL)
			goto end;
		if (debug)
			{
			BIO_set_callback(b64,BIO_debug_callback);
			BIO_set_callback_arg(b64,(char *)bio_err);
			}
		if (olb64)
			BIO_set_flags(b64,BIO_FLAGS_BASE64_NO_NL);
		if (enc)
			wbio=BIO_push(b64,wbio);
		else
			rbio=BIO_push(b64,rbio);
		}

	if (cipher != NULL)
		{
		/* Note that str is NULL if a key was passed on the command
		 * line, so we get no salt in that case. Is this a bug?
		 */
		if (str != NULL)
			{
			/* Salt handling: if encrypting generate a salt and
			 * write to output BIO. If decrypting read salt from
			 * input BIO.
			 */
			unsigned char *sptr;
			if(nosalt) sptr = NULL;
			else {
				if(enc) {
					if(hsalt) {
						if(!set_hex(hsalt,salt,sizeof salt)) {
							BIO_printf(bio_err,
								"invalid hex salt value\n");
							goto end;
						}
					} else if (RAND_pseudo_bytes(salt, sizeof salt) < 0)
						goto end;
					/* If -P option then don't bother writing */
					if((printkey != 2)
					   && (BIO_write(wbio,magic,
							 sizeof magic-1) != sizeof magic-1
					       || BIO_write(wbio,
							    (char *)salt,
							    sizeof salt) != sizeof salt)) {
						BIO_printf(bio_err,"error writing output file\n");
						goto end;
					}
				} else if(BIO_read(rbio,mbuf,sizeof mbuf) != sizeof mbuf
					  || BIO_read(rbio,
						      (unsigned char *)salt,
				    sizeof salt) != sizeof salt) {
					BIO_printf(bio_err,"error reading input file\n");
					goto end;
				} else if(memcmp(mbuf,magic,sizeof magic-1)) {
				    BIO_printf(bio_err,"bad magic number\n");
				    goto end;
				}

				sptr = salt;
			}

			EVP_BytesToKey(cipher,dgst,sptr,
				(unsigned char *)str,
				strlen(str),1,key,iv);
			/* zero the complete buffer or the string
			 * passed from the command line
			 * bug picked up by
			 * Larry J. Hughes Jr. <*****@*****.**> */
			if (str == strbuf)
				OPENSSL_cleanse(str,SIZE);
			else
				OPENSSL_cleanse(str,strlen(str));
			}
		if ((hiv != NULL) && !set_hex(hiv,iv,sizeof iv))
			{
			BIO_printf(bio_err,"invalid hex iv value\n");
			goto end;
			}
		if ((hiv == NULL) && (str == NULL))
			{
			/* No IV was explicitly set and no IV was generated
			 * during EVP_BytesToKey. Hence the IV is undefined,
			 * making correct decryption impossible. */
			BIO_printf(bio_err, "iv undefined\n");
			goto end;
			}
		if ((hkey != NULL) && !set_hex(hkey,key,sizeof key))
			{
			BIO_printf(bio_err,"invalid hex key value\n");
			goto end;
			}

		if ((benc=BIO_new(BIO_f_cipher())) == NULL)
			goto end;

		/* Since we may be changing parameters work on the encryption
		 * context rather than calling BIO_set_cipher().
		 */

		BIO_get_cipher_ctx(benc, &ctx);

		if (non_fips_allow)
			EVP_CIPHER_CTX_set_flags(ctx,
				EVP_CIPH_FLAG_NON_FIPS_ALLOW);

		if (!EVP_CipherInit_ex(ctx, cipher, NULL, NULL, NULL, enc))
			{
			BIO_printf(bio_err, "Error setting cipher %s\n",
				EVP_CIPHER_name(cipher));
			ERR_print_errors(bio_err);
			goto end;
			}

		if (nopad)
			EVP_CIPHER_CTX_set_padding(ctx, 0);

		if (!EVP_CipherInit_ex(ctx, NULL, NULL, key, iv, enc))
			{
			BIO_printf(bio_err, "Error setting cipher %s\n",
				EVP_CIPHER_name(cipher));
			ERR_print_errors(bio_err);
			goto end;
			}

		if (debug)
			{
			BIO_set_callback(benc,BIO_debug_callback);
			BIO_set_callback_arg(benc,(char *)bio_err);
			}

		if (printkey)
			{
			if (!nosalt)
				{
				printf("salt=");
				for (i=0; i<(int)sizeof(salt); i++)
					printf("%02X",salt[i]);
				printf("\n");
				}
			if (cipher->key_len > 0)
				{
				printf("key=");
				for (i=0; i<cipher->key_len; i++)
					printf("%02X",key[i]);
				printf("\n");
				}
			if (cipher->iv_len > 0)
				{
				printf("iv =");
				for (i=0; i<cipher->iv_len; i++)
					printf("%02X",iv[i]);
				printf("\n");
				}
			if (printkey == 2)
				{
				ret=0;
				goto end;
				}
			}
		}

	/* Only encrypt/decrypt as we write the file */
	if (benc != NULL)
		wbio=BIO_push(benc,wbio);

	for (;;)
		{
		inl=BIO_read(rbio,(char *)buff,bsize);
		if (inl <= 0) break;
		if (BIO_write(wbio,(char *)buff,inl) != inl)
			{
			BIO_printf(bio_err,"error writing output file\n");
			goto end;
			}
		}
	if (!BIO_flush(wbio))
		{
		BIO_printf(bio_err,"bad decrypt\n");
		goto end;
		}

	ret=0;
	if (verbose)
		{
		BIO_printf(bio_err,"bytes read   :%8ld\n",BIO_number_read(in));
		BIO_printf(bio_err,"bytes written:%8ld\n",BIO_number_written(out));
		}
end:
	ERR_print_errors(bio_err);
	if (strbuf != NULL) OPENSSL_free(strbuf);
	if (buff != NULL) OPENSSL_free(buff);
	if (in != NULL) BIO_free(in);
	if (out != NULL) BIO_free_all(out);
	if (benc != NULL) BIO_free(benc);
	if (b64 != NULL) BIO_free(b64);
	if(pass) OPENSSL_free(pass);
	apps_shutdown();
	OPENSSL_EXIT(ret);
	}
Beispiel #15
0
/*--------------------------------------------------------------------*/
int mb_fileio_open(int verbose, void *mbio_ptr, int *error)
{
	char	*function_name = "mb_fileio_open";
	int	status = MB_SUCCESS;
	struct mb_io_struct *mb_io_ptr;
	int	fileiobuffer;
	size_t	fileiobufferbytes;
	int	buffer_status = MB_SUCCESS;
	int	buffer_error = MB_ERROR_NO_ERROR;

	/* print input debug statements */
	if (verbose >= 2)
		{
		fprintf(stderr,"\ndbg2  MBIO function <%s> called\n",function_name);
		fprintf(stderr,"dbg2  Revision id: %s\n",rcs_id);
		fprintf(stderr,"dbg2  Input arguments:\n");
		fprintf(stderr,"dbg2       verbose:    %d\n",verbose);
		fprintf(stderr,"dbg2       mbio_ptr:   %p\n",(void *)mbio_ptr);
		}

	/* get mbio descriptor */
	mb_io_ptr = (struct mb_io_struct *) mbio_ptr;

	/* open the file for reading */
	if (mb_io_ptr->filemode == MB_FILEMODE_READ)
		{
		if ((mb_io_ptr->mbfp = fopen(mb_io_ptr->file, "r")) == NULL)
			 {
			 *error = MB_ERROR_OPEN_FAIL;
			 status = MB_FAILURE;
			 }
		}
	else if (mb_io_ptr->filemode == MB_FILEMODE_WRITE)
		{
		if ((mb_io_ptr->mbfp = fopen(mb_io_ptr->file, "wb")) == NULL)
			 {
			 *error = MB_ERROR_OPEN_FAIL;
			 status = MB_FAILURE;
			 }
		}

	/* set buffering if desired
		fileiomode: mode of single normal file i/o:
                        0   use fread() and fwrite() with standard buffering
                        >0  use fread() and fwrite() with user defined buffer
                        <0  use mmap for file i/o */
	if (status == MB_SUCCESS)
		{
		mb_fileiobuffer(verbose, &fileiobuffer);
		if (fileiobuffer > 0)
			{
			/* the buffer size must be a multiple of 512, plus 8 to be efficient */
			fileiobufferbytes = (fileiobuffer * 1024) + 8;

			/* allocate the buffer */
			buffer_error = MB_ERROR_NO_ERROR;
			buffer_status = mb_mallocd(verbose,__FILE__, __LINE__, fileiobufferbytes,
							(void **) &mb_io_ptr->file_iobuffer, &buffer_error);

			/* apply the buffer */
			if (buffer_status == MB_SUCCESS)
				{
				buffer_status = setvbuf(mb_io_ptr->mbfp, mb_io_ptr->file_iobuffer, _IOFBF, fileiobufferbytes);
/* printf(stderr,"Called setvbuf size:%d status:%d\n",fileiobufferbytes,buffer_status); */
				}
			}
		}

	/* print output debug statements */
	if (verbose >= 2)
		{
		fprintf(stderr,"\ndbg2  MBIO function <%s> completed\n",function_name);
		fprintf(stderr,"dbg2  Revision id: %s\n",rcs_id);
		fprintf(stderr,"dbg2  Return values:\n");
		fprintf(stderr,"dbg2       error:      %d\n",*error);
		fprintf(stderr,"dbg2  Return status:\n");
		fprintf(stderr,"dbg2       status:  %d\n",status);
		}

	/* return status */
	return(status);
}
int main(void) {

	setvbuf(stdout, NULL, _IONBF, 0);

	char HtmlDoc[50000];
	char buffer[BUFSIZ + 1];
	char url[BUFSIZ + 1];
	int count = 0;

	printf("URL:\n");
	gets(url);

	char urlString[BUFSIZ + 1];
	strcpy(urlString, "curl -s ");
	strcat(urlString, url);

	fp = popen(urlString, "r");

	char * tempSrc;
	char *pQ1;
	char *pQ2;
	char tempWord[BUFSIZ + 1];
	char * tempTags;
	int numBetween;

	//Reads in the data from the URL
	while (!feof(fp)) {
		numBetween = 0;

		fgets(buffer, BUFSIZ, fp);

		strcat(HtmlDoc, buffer);

		tempSrc = strstr(buffer, "src=");

		if ((tempSrc != NULL) && (isspace(*(tempSrc - 1)))) {
			count++;
			int i = 1;

		}

	}

	pclose(fp);

	printf("Ready\n");

	char command = 'n';
	int done = 0;

	while (done == 0) {

		command = *gets(buffer);
		// A switch that waits for a command to print things
		switch (command) {

		//Prints number of valid src attributes
		case 'c':
			printf("%d\n", count);
			printf("Ready\n");
			break;

			//Prints number of tags
		case 't':
			printTags(HtmlDoc);

			printf("Ready\n");
			break;

			// Prints the URLS
		case 'u':
			printURLS(HtmlDoc);
			printf("Ready\n");
			break;
		case 'f':
			printf("f");
			printf("Ready\n");
			break;

			//Quits the program
		case 'q':

			tempTags = strstr(buffer, "<");

			printf("Complete\n");
			done = 1;
			break;
		}

	}

}
Beispiel #17
0
int
main(int argc, char *argv[])
{
	int clt_sk, svr_sk, accept_sk;
	sockaddr_storage_t svr_loop, accept_loop;
	sockaddr_storage_t svr_local_addr, svr_peer_addr;
	sockaddr_storage_t clt_local_addr, clt_peer_addr;
	socklen_t len;
	int error;
	int pf_class;

        /* Rather than fflush() throughout the code, set stdout to 
	 * be unbuffered.  
	 */ 
	setvbuf(stdout, NULL, _IONBF, 0); 

	/* Initialize the server and client addresses. */ 
#if TEST_V6
	pf_class = PF_INET6;
        svr_loop.v6.sin6_family = AF_INET6;
        svr_loop.v6.sin6_addr = (struct in6_addr)SCTP_IN6ADDR_ANY_INIT;
        svr_loop.v6.sin6_port = htons(SCTP_TESTPORT_1);
#else
	pf_class = PF_INET;
	svr_loop.v4.sin_family = AF_INET;
	svr_loop.v4.sin_addr.s_addr = INADDR_ANY;
	svr_loop.v4.sin_port = htons(SCTP_TESTPORT_1);
#endif

	/* Create and bind the listening server socket.  */
        svr_sk = test_socket(pf_class, SOCK_STREAM, IPPROTO_SCTP);
	test_bind(svr_sk, &svr_loop.sa, sizeof(svr_loop));

	memset(&svr_local_addr, 0x00, sizeof(svr_local_addr));
	len = sizeof(svr_local_addr);
	/* Verify that getsockname() on an unconnected socket works fine. */
	error = getsockname(svr_sk, (struct sockaddr *)&svr_local_addr, &len);
	if (0 != error)
		tst_brkm(TBROK, tst_exit, "getsockname: %s", strerror(errno));

	tst_resm(TPASS, "getsockname on an unconnected socket");

	memset(&svr_peer_addr, 0x00, sizeof(svr_peer_addr));
	len = sizeof(svr_peer_addr);
	/* Verify that getpeername() on an unconnected socket fails. */
	error = getpeername(svr_sk, (struct sockaddr *)&svr_peer_addr, &len);
	if ((-1 != error) || (ENOTCONN != errno))
		tst_brkm(TBROK, tst_exit, "getpeername on an unconnected "
			 "socket error:%d, errno:%d", error, errno);

	tst_resm(TPASS, "getpeername on an unconnected socket");

	/* Mark svr_sk as being able to accept new associations.  */
	test_listen(svr_sk, 5);

	/* Create the client socket.  */
	clt_sk = test_socket(pf_class, SOCK_STREAM, IPPROTO_SCTP);
	
	/* Do a blocking connect from clt_sk to svr_sk */      
#if TEST_V6
	svr_loop.v6.sin6_addr = in6addr_loopback;
#else
	svr_loop.v4.sin_addr.s_addr = SCTP_IP_LOOPBACK;
#endif
	test_connect(clt_sk, &svr_loop.sa, sizeof(svr_loop));

	memset(&clt_local_addr, 0x00, sizeof(clt_local_addr));
	len = sizeof(clt_local_addr);
	/* Get the client's local address. */
	error = getsockname(clt_sk, (struct sockaddr *)&clt_local_addr, &len);
	if (0 != error)
		tst_brkm(TBROK, tst_exit, "getsockname on a connected client "
			 "socket: %s", strerror(errno));

	tst_resm(TPASS, "getsockname on a connected client socket");

	memset(&clt_peer_addr, 0x00, sizeof(clt_peer_addr));
	len = sizeof(clt_peer_addr);
	/* Get the client's peer address. */
	error = getpeername(clt_sk, (struct sockaddr *)&clt_peer_addr, &len);
	if (0 != error)
		tst_brkm(TBROK, tst_exit, "getpeername on a connected client "
			 "socket: %s", strerror(errno));

	tst_resm(TPASS, "getpeername on a connected client socket");

	/* Extract the association on the listening socket as a new socket. */
	len = sizeof(accept_loop);
	accept_sk = test_accept(svr_sk, &accept_loop.sa, &len); 

	memset(&svr_local_addr, 0x00, sizeof(svr_local_addr));
	len = sizeof(svr_local_addr);
	/* Get the server's local address. */
	error = getsockname(accept_sk, (struct sockaddr *)&svr_local_addr,
				&len);
	if (0 != error)
		tst_brkm(TBROK, tst_exit, "getsockname on a connected server "
			 "socket: %s", strerror(errno));

	tst_resm(TPASS, "getsockname on a connected server socket");

	memset(&svr_peer_addr, 0x00, sizeof(svr_peer_addr));
	len = sizeof(svr_peer_addr);
	/* Get the server's peer address. */
	error = getpeername(accept_sk, (struct sockaddr *)&svr_peer_addr,
				&len);
	if (0 != error)
		tst_brkm(TBROK, tst_exit, "getpeername on a connected server "
			 "socket: %s", strerror(errno));

	tst_resm(TPASS, "getpeername on a connected server socket");

	if (svr_local_addr.v4.sin_port != clt_peer_addr.v4.sin_port)
		tst_brkm(TBROK, tst_exit, "Server's local port(%d) doesn't "
			 "match Client's peer port(%d)\n",
			 svr_local_addr.v4.sin_port, clt_peer_addr.v4.sin_port);

	if (svr_peer_addr.v4.sin_port != clt_local_addr.v4.sin_port)
		tst_brkm(TBROK, tst_exit, "Server's peer port(%d) doesn't "
			 "match Client's local port(%d)\n",
			 svr_peer_addr.v4.sin_port, clt_local_addr.v4.sin_port);
#if TEST_V6
	if (memcmp(&svr_local_addr, &clt_peer_addr, len) != 0)
		tst_brkm(TBROK, tst_exit, "Server's local address and client's "
			 "peer addresses do not match\n");

	if (memcmp(&svr_peer_addr, &clt_local_addr, len) != 0)
		tst_brkm(TBROK, tst_exit, "Server's peer address and client's "
			 "local addresses do not match\n");
#else
	if (svr_local_addr.v4.sin_addr.s_addr !=
		 		clt_peer_addr.v4.sin_addr.s_addr)
		tst_brkm(TBROK, tst_exit, "Server's local address and client's "
			 "peer addresses do not match\n");
	if (svr_peer_addr.v4.sin_addr.s_addr !=
		 		clt_local_addr.v4.sin_addr.s_addr)
		tst_brkm(TBROK, tst_exit, "Server's peer address and client's "
			 "local addresses do not match\n");
#endif
	tst_resm(TPASS, "getsockname/getpeername server/client match");

	memset(&clt_local_addr, 0x00, sizeof(clt_local_addr));
	len = sizeof(clt_local_addr);
	/*getsockname():  Bad socket descriptor, EBADF expected error*/
	error = getsockname(-1, (struct sockaddr *)&clt_local_addr, &len);
	if (error != -1 || errno != EBADF)
		tst_brkm(TBROK, tst_exit, "getsockname on a bad socket "
			 "descriptor. error:%d errno:%d", error, errno);

	tst_resm(TPASS, "getsockname on a bad socket descriptor - EBADF");

	/*getsockname(): Invalid socket, ENOTSOCK expected error*/
	error = getsockname(0, (struct sockaddr *)&clt_local_addr, &len);
	if (error != -1 || errno != ENOTSOCK)
		tst_brkm(TBROK, tst_exit, "getsockname on an invalid socket "
			 "error:%d errno:%d", error, errno);

	tst_resm(TPASS, "getsockname on an invalid socket - ENOTSOCK");

	/*getsockname(): Invalid structure, EFAULT expected error*/
	error = getsockname(clt_sk, (struct sockaddr *)-1, &len);
	if (error != -1 || errno != EFAULT)
		tst_brkm(TBROK, tst_exit, "getsockname with invalid buffer "
			 "error:%d errno:%d", error, errno);

	tst_resm(TPASS, "getsockname with invalid buffer - EFAULT");
 
	memset(&clt_peer_addr, 0x00, sizeof(clt_peer_addr));
	len = sizeof(clt_peer_addr);
	/*getpeername():  Bad socket descriptor, EBADF expected error*/
	error = getpeername(-1, (struct sockaddr *)&clt_local_addr, &len);
	if (error != -1 || errno != EBADF)
		tst_brkm(TBROK, tst_exit, "getpeername on a bad socket "
			 "descriptor. error:%d errno:%d", error, errno);

	tst_resm(TPASS, "getpeername on a bad socket descriptor - EBADF");

	/*getpeername(): Invalid socket, ENOTSOCK expected error*/
	error = getpeername(0, (struct sockaddr *)&clt_local_addr, &len);
	if (error != -1 || errno != ENOTSOCK)
		tst_brkm(TBROK, tst_exit, "getpeername on an invalid socket "
			 "error:%d errno:%d", error, errno);

	tst_resm(TPASS, "getpeername on an invalid socket - ENOTSOCK");

	/*getpeername(): Invalid structure, EFAULT expected error*/
	error = getpeername(clt_sk, (struct sockaddr *)-1, &len);
	if (error != -1 || errno != EFAULT)
		tst_brkm(TBROK, tst_exit, "getpeername with invalid buffer "
			 "error:%d errno:%d", error, errno);

	tst_resm(TPASS, "getpeername with invalid buffer - EFAULT");
 
	close(clt_sk);
	close(svr_sk);
	close(accept_sk);

        /* Indicate successful completion.  */
	return 0;
}
Beispiel #18
0
void os_set_line_buffering(void)
{
    setvbuf(stdout, NULL, _IOLBF, 0);
}
int main(int argc, const char * argv[]) {
    
    srand(time(NULL));  // ensures that different random numbers are generated every time a program is run;
    setvbuf(stdout, NULL, _IONBF, 0);
    
    char map[12][30];
    int minelist[2][10];
    int i, j, count = 0, c;
    
    // stores '.' signs in an array "map":
    for (i = 0; i<12; i++) {
        for (j = 0; j<30; j++) {
            map[i][j] = '.';
        }
    }
    
    // generates coordinates of mines and stores these values to an array "minelist":
    for (c = 0; c<10; c++) {
        minelist[0][c] = (rand() % 12);
        minelist[1][c] = (rand() % 30);
    }
    
    // replaces '.' signs in array "map" by '*' signs according to the coordinates stores in "minelist":
    for (c = 0; c < 10; c++) {
        i = minelist[0][c];
        j = minelist[1][c];
        map[i][j] = '*';
    }
    
    // changes value of each cell according to the number of "*" signs in neighbouring cells:
    for (i = 0; i < 12; i++) {
        for (j = 0; j < 30; j++) {
            if (map[i][j] == '.') {
                if (!(i-1<0) && !(j-1<0)) {
                    if (map[i-1][j-1] == '*') {
                       count++;
                    }
                }
                
                if (!(i-1<0) && !(j>29)) {
                    if (map[i-1][j] == '*') {
                       count++;
                    }
                }
                
                if (!(i-1<0) && !(j+1>29)) {
                    if (map[i-1][j+1] == '*') {
                       count++;
                    }
                }
            
                if (!(i<0) && !(j-1<0)) {
                    if (map[i][j-1] == '*') {
                       count++;
                    }
                }
            
                if (!(i<0) && !(j+1>29)) {
                    if (map[i][j+1] == '*') {
                       count++;
                    }
                }
            
                if (!(i+1>11) && !(j-1<0)) {
                    if(map[i+1][j-1] == '*') {
                       count++;
                    }
                }
        
                if (!(i+1>11) && !(j>29)) {
                    if (map[i+1][j] == '*') {
                       count++;
                    }
                }
                
                if (!(i+1>11) && !(j+1>29)) {
                    if (map[i+1][j+1] == '*') {
                       count++;
                    }
                }
                
                if (count > 0) {
                    map[i][j] = count + '0';  // if at least 1 '*' sign was found, replaces the value of a cell by a count;
                    count = 0;
                } else {
                    map[i][j] = '.'; // if no such sign was found, the initial value remains;
                }
            }
        }
    }
    
    _Bool view[12][30];  // an array that stores the values of uncovered cells;
    int x, y;
    int guess_count = 0;  // is used to count the number of trials made by the user;
    
    for (i = 0; i<12; i++) {
        for (j = 0; j<30; j++) {
            view[i][j] = 0;  // in the beginning sets all values false;
        }
    }
    
    do {
        // gets corresponding coordinates from the user:
       printf("Type in a number of row: ");
       scanf("%i", &x);
       printf("Type in a number of column: ");
       scanf("%i", &y);

        // checks if given numbers are in a range, if not the program keeps asking for new numbers unless they are valid:
       if (x<=0 || x>12 || y<=0 || y>30) {
          do {
              printf("Invalid value \n");
              printf("Type in a number of row: ");
              scanf("%i", &x);
              printf("Type in a number of column: ");
              scanf("%i", &y);
          } while (!((x>0) && (x<13) && (y>0) && (y<31)));
       }
    
       i = x-1;
       j = y-1;
      
       view[i][j] = 1; // changes the value of according coordinates in an array to true;
       char ch = '?';

        if (map[i][j] == '*') {
            for (i = 0; i<12; i++) {
                for (j = 0; j<30; j++) {
                    printf("%2c", map[i][j]);
                }
                printf("\n");
            }
            printf("BOOOOM! Game is over!\n");  // if a mine was uncovered, ends the program;
            break;
        } else {
               for (i = 0; i<12; i++) {
                   for (j = 0; j<30; j++) {
                       if (view[i][j] == 1) {
                          printf("%2c", map[i][j]);
                       } else if (view[i][j] == 0) {
                          printf("%2c", ch);
                       }
                   }
                   printf("\n");
               }
            guess_count++; // if a mine was not uncovered, shows the values of "map" which are true in "view", while others are replaced by a "?" sign;
        }
    } while (guess_count < 350);
    
    if (guess_count >= 350) {
       printf("CONGRATULATIONS!\n"); // the maximum possible number of guesses is 350, so if the count exceeds, then the player must be the winner;
    }
    
    return 0;
}
Beispiel #20
0
Static void
INIT_DEFAULTS(int Echo)
{

/* These can be removed, they are not used functionally.  Only to keep
   some having to change some function parameters.
*/
char Device[30];
    Test_Com = __default_test_term;
    Ref_Com = __default_ref_term;
    Aux_A_Com = __default_aux_a;
    Aux_B_Com = __default_aux_b;
    __Refpres = (__default_ref_term != 0);
    __Aux_A_Pres = (__default_aux_a != 0);
    __Aux_B_Pres = (__default_aux_b != 0);
    __Data_Com[0] = __default_datacom_rec;
    __Data_Com[1] = __default_datacom_rec;
    __Data_Com[2] = __default_datacom_rec;
    __Data_Com[3] = __default_datacom_rec;
    /* __Rs_Time_Out = false;               */
/* ****************************************************************/ 

    /* Open /dev/tty and obtain file descriptor and FILE pointer. */
    if((fd_test = open("/dev/tty", O_RDWR)) < 0) {
      (void) perror("INIT_DEFAULTS: /dev/tty open:");
      (void) exit(1);
    }

    f_test = fdopen(fd_test, "w"); 
    (void) setvbuf(f_test, (char *) 0, _IONBF, 0);

    /* get struct termio for later restoration and use for setting defaults */
    if(tcgetattr(fd_test, &termio_orig) < 0) {
      (void) perror("INIT_DEFAULTS: tcgetattr:");
      (void) exit(1);
    }
    
    /* Default settings determined from PANACOM tests, and translated to
       HP_UX environment. Along with default settings using struct termios. */

/* Canonical Input is OFF  */

    termio_test = termio_orig;
    termio_test.c_iflag &= ~(ICRNL | IUCLC | IXANY);
    termio_test.c_iflag |= (IXON | IXOFF);  
    termio_test.c_lflag &= ~(ICANON | ECHO);
    termio_test.c_cflag |= (CS8 | CREAD);
    termio_test.c_cc[VMIN] = 1;    
    termio_test.c_cc[VTIME] = 0;  
  
   
/* Canonical Input is ON  */
/*
   termio_test = termio_orig;
   termio_test.c_iflag |= (IXON | IXOFF);
   termio_test.c_lflag |= (ICANON);
   termio_test.c_lflag &= ~(ECHO);
   termio_test.c_cflag |= CS8; 
   termio_test.c_cc[VINTR] = _POSIX_VDISABLE;
   termio_test.c_cc[VQUIT] = _POSIX_VDISABLE;
   termio_test.c_cc[VERASE] = _POSIX_VDISABLE;
   termio_test.c_cc[VKILL] = _POSIX_VDISABLE;
   termio_test.c_cc[VEOF] = _POSIX_VDISABLE;
*/
     


/* turn on signal handlers... */
    (void) signal(SIGHUP, cleanup);
    (void) signal(SIGINT, cleanup);
    (void) signal(SIGQUIT, cleanup);
    (void) signal(SIGTERM, cleanup);

    /* set a 2 minute timeout... */
    (void) signal(SIGALRM, timeout);
    /* (void) alarm(240);  */


    /* set new terminal control attributes */
    if(tcsetattr(fd_test,TCSADRAIN,&termio_test) < 0) {
      (void) perror("tcsetattr New");
      (void) exit(1);
    }

    /* default terminal settings  */
    SPEEDTEST(B9600);
    PARITYTEST("4");                  /* 8 bit no parity */
    HANDSHAKE_COM("X");               /* IXON and IXOFF  */
    if (Echo) ECHO_COM("ON");         /* echoing on     */
    else ECHO_COM("OFF");         /* echoing off     */

}
int main(int argc, char* argv[])
{
    char hostName[200] = DEFAULT_HOSTNAME;
    int port = DEFAULT_RESMGR_TPM_PORT;

    TPMI_DH_OBJECT objectHandle;
    char outFilePath[PATH_MAX] = {0};
    char *contextFile = NULL;

    setbuf(stdout, NULL);
    setvbuf (stdout, NULL, _IONBF, BUFSIZ);

    int opt = -1;
    const char *optstring = "hvH:o:p:d:c:";
    static struct option long_options[] = {
      {"help",0,NULL,'h'},
      {"version",0,NULL,'v'},
      {"object",1,NULL,'H'},
      {"opu",1,NULL,'o'},
      {"port",1,NULL,'p'},
      {"debugLevel",1,NULL,'d'},
      {"contextObject",1,NULL,'c'},
      {0,0,0,0}
    };

    int returnVal = 0;
    int flagCnt = 0;
    int h_flag = 0,
        v_flag = 0,
        H_flag = 0,
        c_flag = 0,
        o_flag = 0;

    if(argc == 1)
    {
        showHelp(argv[0]);
        return 0;
    }

    while((opt = getopt_long(argc,argv,optstring,long_options,NULL)) != -1)
    {
        switch(opt)
        {
        case 'h':
            h_flag = 1;
            break;
        case 'v':
            v_flag = 1;
            break;
        case 'H':
            if(getSizeUint32Hex(optarg,&objectHandle) != 0)
            {
                returnVal = -1;
                break;
            }
            printf("\nobject handle: 0x%x\n\n",objectHandle);
            H_flag = 1;
            break;
        case 'o':
            safeStrNCpy(outFilePath, optarg, sizeof(outFilePath));
            if(checkOutFile(outFilePath) != 0)
            {
                returnVal = -2;
                break;
            }
            o_flag = 1;
            break;
        case 'p':
            if( getPort(optarg, &port) )
            {
                printf("Incorrect port number.\n");
                returnVal = -3;
            }
            break;
        case 'd':
            if( getDebugLevel(optarg, &debugLevel) )
            {
                printf("Incorrect debug level.\n");
                returnVal = -4;
            }
            break;
        case 'c':
            contextFile = optarg;
            if(contextFile == NULL || contextFile[0] == '\0')
            {
                returnVal = -5;
                break;
            }
            printf("contextFile = %s\n", contextFile);
            c_flag = 1;
            break;
        case ':':
//              printf("Argument %c needs a value!\n",optopt);
            returnVal = -6;
            break;
        case '?':
//              printf("Unknown Argument: %c\n",optopt);
            returnVal = -7;
            break;
        //default:
        //  break;
        }
        if(returnVal)
            break;
    };

    if(returnVal != 0)
        return returnVal;

    flagCnt = h_flag + v_flag + H_flag + o_flag + c_flag;
    if(flagCnt == 1)
    {
        if(h_flag == 1)
            showHelp(argv[0]);
        else if(v_flag == 1)
            showVersion(argv[0]);
        else
        {
            showArgMismatch(argv[0]);
            return -8;
        }
    }
    else if(flagCnt == 2 && (H_flag == 1 || c_flag) && o_flag == 1)
    {
        prepareTest(hostName, port, debugLevel);

        if(c_flag)
            returnVal = loadTpmContextFromFile(sysContext, &objectHandle, contextFile);
        if(returnVal == 0)
            returnVal = readPublic(objectHandle, outFilePath);

        finishTest();

        if(returnVal)
            return -9;
    }
    else
    {
        showArgMismatch(argv[0]);
        return -10;
    }

    return 0;
}
int main(int argc, char **argv)
{
    setvbuf(stdout, NULL, _IOLBF, 0);
#ifdef XP_UNIX
    unlimit();
#endif
    fprintf(stdout, "\n");

    unsigned long limit = 0; // no thread limit by default
    char *addr = NULL;
    PRBool log = PR_FALSE;
    LogLevel logLevel = LOGINFO;
    PLOptState *options;
    PRBool secure = PR_FALSE;
    PRBool NSTests = PR_FALSE; // don't execute Netscape tests by default
    PtrList<char> protlist; // list of security protocols
    PtrList<char> configlist; // list of configurations
    RegexList regexlist; // list of Sun tests/regex to load
    RegexList regexcludelist; // list of Sun tests/regex to exclude
    char* suitename = "suite1";
    PRInt32 concurrent = 0; // number of concurrent threads for each test. 0 means sequential, single-threaded
    PRInt32 delay = 0;
    PRInt32 split = 0;
    PRInt32 timeout = 0; // leave timeout unchanged by default
    char* cert=NULL;
    char* certpwd=NULL;
    char* cipherString = NULL;
    char* version = "ENTERPRISE";
    PRInt32 release = 41;
    PRInt32 hsp = 0; // SSL handshake period
    PRBool performance = PR_FALSE;
    PRInt32 maxtm = 0;
    PRUint16 af = PR_AF_INET;
    PRInt32 displayperiod=0;
    PRBool loop = PR_FALSE;

    Logger::logInitialize(logLevel);

    options = PL_CreateOptState(argc, argv, "X:C:h:H:l:c:d:n:w46r:sx:p:o:t:a:e:k:Ng:v:R:QPE:T:L:");
    long repeat = 1;
    while ( PL_GetNextOpt(options) == PL_OPT_OK)
    {
        switch(options->option)
        {
            case 'L':
                loop = PR_TRUE;
                if (options->value)
                    displayperiod  = (PRInt32) atoi(options->value);
                break;

            case 'E':
                if (options->value)
                    protlist.insert(strdup(options->value));
                break;

            case 'T':
                if (options->value)
                    maxtm  = (PRInt32) atoi(options->value);
                break;

            case 'H':
                if (options->value)
                    hsp  = (PRInt32) atoi(options->value);
                break;

            case 'v':
                if (options->value)
                    version = uppercase(strdup(options->value));
                break;

            case 'g':
                if (options->value)
                    configlist.insert(strdup(options->value));
                break;

            case 'x':
                if (options->value)
                    regexlist.add(options->value);
                break;

            case 'X':
                if (options->value)
                    regexcludelist.add(options->value);
                break;

            case 'w':
                log = PR_TRUE;
                break;

            case 'r':
                if (options->value)
                    repeat = atol(options->value);
                break;

            case 'e':
                if (options->value)
                    timeout = atol(options->value);
                break;

            case 'o':
                if (options->value)
                    split = atol(options->value);
                break;

            case 't':
                if (options->value)
                    delay = atol(options->value);
                break;

            case 'd':
                if (options->value)
                   suitename = strdup(options->value);
                break;

            case 'a':
                if (options->value)
                    arch = strdup(options->value);
                break;

            case 'N':
                NSTests = PR_TRUE;
                break;

            case 'h':
                if (options->value)
                    addr = strdup(options->value);
                break;

            case 'p':
                if (options->value)
                    concurrent = atol(options->value);
                else
                    concurrent = 1; // 1 thread per test
                break;

            case 'P':
                performance = PR_TRUE; // meaure performance only
                break;

            case 'l':
                if (options->value)
                    logLevel = (LogLevel)atoi(options->value);
                break;

            case 'R':
                if (options->value)
                    release = (PRInt32) atoi(options->value);
                break;

            case 's':
                secure = PR_TRUE;
                break;

            case 'n':
                if (options->value)
                    cert = strdup(options->value);
                break;

            case 'k':
                if (options->value)
                    certpwd = strdup(options->value);
                break;

            case 'c':
		if (options->value) {
                  cipherString = strdup(options->value);
                  if (PR_TRUE != EnableCipher(cipherString))
                  {
                         Logger::logError(LOGINFO, "Invalid cipher specified.\n");
                   };
                 }
 		 break;


            case 'C':
                if (options->value)
                    limit = atol(options->value);
                else
                    limit = 0; // no thread limit
                break;

	    case 'Q':
		printCipherOptions();
		break;

	    case '6':
                af = PR_AF_INET6;
		break;

	    case '4':
                af = PR_AF_INET;
		break;

        };
    };

    SecurityProtocols secprots;

    if (PR_TRUE == secure)
    {
        NSString str;
        str.append(suitename);
        str.append("/certs/client");
        secure = InitSecurity((char*)str.data(),
            cert,
            certpwd);
        if (PR_TRUE != secure)
            Logger::logError(LOGINFO, "Unable to initialize security.\n");

        if (protlist.entries())
        {
            secprots = protlist;
        };
    };

    PL_DestroyOptState(options);

    Logger::logInitialize(logLevel);
    nstime_init();

    if (!addr)
    {
        usage(argv[0]);
        return -1;
    };

    HttpServer server(addr, af);
    server.setSSL(secure);
    
    if (PR_FALSE == NSTests)
    {
        if (alltests)
            alltests->clear(); // cancel all the Netscape tests
        if (!regexlist.length())
            regexlist.add(".*");
    };

    if (!configlist.entries())
        configlist.insert("COMMON"); // if no config is specified, select default COMMON configuration

    Engine::globaltimeout = PR_TicksPerSecond()*timeout;

    SunTestSuite suite(configlist, suitename, regexlist, regexcludelist, arch, version, release, log, PR_TicksPerSecond()*timeout, split, delay, hsp, secprots, maxtm);
    PRInt32 percent = suite.runTests(server, concurrent, repeat, limit, performance, loop, displayperiod);

    return percent;
};
GifFileType *
DGifOpenFileHandle(int FileHandle) {

    unsigned char Buf[GIF_STAMP_LEN + 1];
    GifFileType *GifFile;
    GifFilePrivateType *Private;
    FILE *f;

    GifFile = (GifFileType *)malloc(sizeof(GifFileType));
    if (GifFile == NULL) {
        _GifError = D_GIF_ERR_NOT_ENOUGH_MEM;
        close(FileHandle);
        return NULL;
    }

    memset(GifFile, '\0', sizeof(GifFileType));

    Private = (GifFilePrivateType *)malloc(sizeof(GifFilePrivateType));
    if (Private == NULL) {
        _GifError = D_GIF_ERR_NOT_ENOUGH_MEM;
        close(FileHandle);
        free((char *)GifFile);
        return NULL;
    }
#if defined(__MSDOS__) || defined(WINDOWS32) || defined(_OPEN_BINARY)
    setmode(FileHandle, O_BINARY);    /* Make sure it is in binary mode. */
#endif /* __MSDOS__ */

    f = fdopen(FileHandle, "rb");    /* Make it into a stream: */

#if defined(__MSDOS__) || defined(WINDOWS32)
    setvbuf(f, NULL, _IOFBF, GIF_FILE_BUFFER_SIZE);    /* And inc. stream
                                                          buffer. */
#endif /* __MSDOS__ */

    GifFile->Private = (VoidPtr)Private;
    Private->FileHandle = FileHandle;
    Private->File = f;
    Private->FileState = FILE_STATE_READ;
    Private->Read = 0;    /* don't use alternate input method (TVT) */
    GifFile->UserData = 0;    /* TVT */

    /* Lets see if this is a GIF file: */
    if (READ(GifFile, Buf, GIF_STAMP_LEN) != GIF_STAMP_LEN) {
        _GifError = D_GIF_ERR_READ_FAILED;
        fclose(f);
        free((char *)Private);
        free((char *)GifFile);
        return NULL;
    }

    /* The GIF Version number is ignored at this time. Maybe we should do
     * something more useful with it.  */
    Buf[GIF_STAMP_LEN] = 0;
    if (strncmp(GIF_STAMP, Buf, GIF_VERSION_POS) != 0) {
        _GifError = D_GIF_ERR_NOT_GIF_FILE;
        fclose(f);
        free((char *)Private);
        free((char *)GifFile);
        return NULL;
    }

    if (DGifGetScreenDesc(GifFile) == GIF_ERROR) {
        fclose(f);
        free((char *)Private);
        free((char *)GifFile);
        return NULL;
    }

    _GifError = 0;

    return GifFile;
}
Beispiel #24
0
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] )
{
	unsigned short wDataFormat;
	mxArray ** nTestType     = &plhs[0];
	mxArray ** szComment     = &plhs[1];
	mxArray ** nSpikeChannel = &plhs[2];
	mxArray ** aTestType     = &plhs[3];
	mxArray ** aExpParam     = &plhs[4];
	mxArray ** aBehavParam   = &plhs[5];
	mxArray ** aGraphParam   = &plhs[6];
	mxArray ** aTestSeries   = &plhs[7];
	mxArray ** aTrial        = &plhs[8];
	mxArray ** aFOREP        = &plhs[9];
	mxArray ** aResponseTime = &plhs[10];
	mxArray ** aTrialStatus  = &plhs[11];
	mxArray ** aDepth2Match  = &plhs[12];
	mxArray ** aCursorDepth  = &plhs[13];
	mxArray ** ucMajorChannel= &plhs[14];
	mxArray ** nCellNum      = &plhs[15];
	mxArray ** ucElectrodeNum= &plhs[16];
	mxArray ** nElectrodeDepth=&plhs[17];
    mxArray ** fSpikeShape           = &plhs[18];
    mxArray ** nSpikeShapeTimes      = &plhs[19];
    mxArray ** dSpikeShapeTimestamp  = &plhs[20];
    mxArray ** nSpikeShapeSampleRate = &plhs[21];

	int dims[2];
	FILE * fp;
	char * szFileName;
	size_t buflen = mxGetM(prhs[0]) * mxGetN(prhs[0]) + 1;
    unsigned long dwCount;
    int i, j;
    mxArray * array;

	szFileName = mxCalloc( buflen, sizeof(char) );
	mxGetString(prhs[0], szFileName, buflen);

	if( !(fp = fopen( szFileName, "rb" )) )
	{
		printf( "Can't open file!\n" );
		return;
	}
	setvbuf( fp, NULL, _IOFBF, 32000 );

	dims[0] = 1;
	dims[1] = 1;
	*nTestType = mxCreateNumericArray( 2, dims, mxINT32_CLASS, mxREAL );
	*nSpikeChannel = mxCreateNumericArray( 2, dims, mxINT32_CLASS, mxREAL );
	*ucMajorChannel = mxCreateNumericArray( 2, dims, mxUINT8_CLASS, mxREAL );
    *nSpikeShapeSampleRate = mxCreateNumericArray( 2, dims, mxINT32_CLASS, mxREAL );
	dims[1] = 8;
	*nCellNum = mxCreateNumericArray( 2, dims, mxINT16_CLASS, mxREAL );
	*ucElectrodeNum = mxCreateNumericArray( 2, dims, mxUINT8_CLASS, mxREAL );
	*nElectrodeDepth = mxCreateNumericArray( 2, dims, mxINT16_CLASS, mxREAL );

	fread( &wDataFormat, 2, 1, fp );
	if(wDataFormat > 10) {
	    printf("The format of underlining VLab file is newer than expected! !\n");
	    /*this piece of code actually reads data up to wDataFormat = 2*/
	    /*return;*/
	}
	fread( mxGetData(*nTestType), 4, 1, fp );
	if( wDataFormat == 0 || wDataFormat >= 2 )
		*szComment = ReadCString( fp );
	else
		*szComment = mxCreateString( mxCalloc( 1, sizeof(char) ) );
	fread( mxGetData(*nSpikeChannel), 4, 1, fp );
	if( wDataFormat > 0 )
	{
		fread( mxGetData(*ucMajorChannel), 1, 1, fp );
		fread( mxGetData(*nCellNum), 2, 8, fp );
		fread( mxGetData(*ucElectrodeNum), 1, 8, fp );
		fread( mxGetData(*nElectrodeDepth), 2, 8, fp );
	}

	*aTestType = ReadCStringArray( fp );

	ClassName = (char**)mxCalloc( 1, sizeof(char*) );
	sizeClassName = 0;

	*aExpParam = ReadCTypedPtrArray( fp );
	*aBehavParam = ReadCTypedPtrArray( fp );
	*aGraphParam = ReadCTypedPtrArray( fp );
	*aTestSeries = ReadCStringArray( fp );
	*aTrial = ReadCTypedPtrArray( fp );
	*aFOREP = ReadCArray( fp, mxINT32_CLASS );
	*aResponseTime = ReadCArray( fp, mxINT32_CLASS );
	*aTrialStatus = ReadCArray( fp, mxINT32_CLASS );
	*aDepth2Match = ReadCArray( fp, mxINT32_CLASS );
	*aCursorDepth = ReadCArray( fp, mxINT32_CLASS );

    /* spike shape */
    if (wDataFormat >= 10) {
        *fSpikeShape = mxCreateCellMatrix(8, 1);
        *nSpikeShapeTimes = mxCreateCellMatrix(8, 1);
        for (i = 0; i < 8; i ++) {
            dwCount = ReadCount( fp );
            array = mxCreateCellMatrix(dwCount, 1);
            for (j = 0; j < (int)dwCount; j ++)
                mxSetCell( array, j, ReadCArray(fp, mxSINGLE_CLASS));
            mxSetCell(*fSpikeShape, i, array);
            mxSetCell(*nSpikeShapeTimes, i, ReadCArray(fp, mxINT32_CLASS));
        }
        *dSpikeShapeTimestamp = ReadCArray(fp, mxUINT32_CLASS);
        dims[1] = 1;
        *nSpikeShapeSampleRate = mxCreateNumericArray( 2, dims, mxINT32_CLASS, mxREAL );
        fread(mxGetData(*nSpikeShapeSampleRate), 4, 1, fp );
    }
	else
	{
        *fSpikeShape = mxCreateCellMatrix(8, 1);
        *nSpikeShapeTimes = mxCreateCellMatrix(8, 1);
        dims[1] = 1;
        *dSpikeShapeTimestamp = mxCreateNumericArray(2, dims, mxUINT32_CLASS, mxREAL);
        *nSpikeShapeSampleRate = mxCreateNumericArray(2, dims, mxINT32_CLASS, mxREAL);
	}
	fclose( fp );

	mxFree( ClassName );
	ClassName = NULL;
}
Beispiel #25
0
int main(int argc, char ** argv)
{
    char * sender;

    char * message;
    unsigned int time_message;
    unsigned int timer;
    unsigned int num;
    char * message_filename;
    char * dir;

    char * ptr;
    char * my_delivered_to;

    DIR * dirp;
    struct dirent * direntp;
    unsigned int message_time;
    char * address;
    unsigned int count;
    char filename[256];
    FILE * f;
    unsigned int message_handling = DEFAULT_MH;
    char buffer[256];
    char *content_boundary;
    char *rpath = DEFAULT_FROM;
    char *TheUser;
    char *TheDomain;

    if(argc > 7 || argc < 5) {
        fprintf(stderr, "\nautorespond: ");
        fprintf(stderr, "usage: time num message dir [ flag arsender ]\n\n");
        fprintf(stderr, "time - amount of time to consider a message (in seconds)\n");
        fprintf(stderr, "num - maximum number of messages to allow within time seconds\n");
        fprintf(stderr, "message - the filename of the message to send\n");
        fprintf(stderr, "dir - the directory to hold the log of messages\n\n");
        fprintf(stderr, "optional parameters:\n\n");
        fprintf(stderr, "flag - handling of original message:\n\n");
        fprintf(stderr, "0 - append nothing\n");
        fprintf(stderr, "1 - append quoted original message without attachments <default>\n\n");
        fprintf(stderr, "arsender - from address in generated message, or:\n\n");
        fprintf(stderr, "+ = blank from envelope !\n");
        fprintf(stderr, "$ = To: address will be used\n\n");
        _exit(111);
    }

    TheUser= getenv("EXT");
    TheDomain= getenv("HOST");

    setvbuf(stderr, NULL, _IONBF, 0);

    if(argc > 7 || argc < 5) {
        fprintf(stderr, "AUTORESPOND: Invalid arguments. (%d)\n",argc);
        _exit(111);
    }

    time_message     = strtoul(argv[1],NULL,10);
    num              = strtoul(argv[2],NULL,10);
    message_filename = argv[3];
    dir              = argv[4];

    if ( argc > 5 )
        message_handling = strtoul(argv[5],NULL,10);
    if ( argc > 6 )
        rpath = argv[6];

    if ( *rpath == '+' )
        rpath = "";
    if ( *rpath == '$' )
    {
        rpath = safe_malloc( strlen(TheUser) + strlen(TheDomain) + 2);
        strncpy( rpath, TheUser, strlen(TheUser) );
        strncat( rpath, "@", 1 );
        strncat( rpath, TheDomain, strlen(TheDomain) );
    }

    timer = time(NULL);

    /*prepare the "delivered-to" string*/
    my_delivered_to = "Delivered-To: Autoresponder\n";

    read_headers( stdin );


    message = read_file(message_filename);
    if(message==NULL) {
        fprintf(stderr, "AUTORESPOND: Failed to open message file.\n");
        _exit(111);
    }

    /*don't autorespond in certain situations*/
    sender = getenv("SENDER");
    if(sender==NULL)
        sender = "";

    /*don't autorespond to a mailer-daemon*/
    if( sender[0]==0 || strncasecmp(sender,"mailer-daemon",13)==0 || strchr(sender,'@')==NULL || strcmp(sender,"#@[]")==0 ) {
        /*exit with success and continue parsing .qmail file*/
        fprintf(stderr,"AUTORESPOND:  Stopping on mail from [%s].\n",sender);
        _exit(0);
    }


    if ( inspect_headers("mailing-list", (char *)NULL ) != (char *)NULL )
    {
        fprintf(stderr,"AUTORESPOND: This looks like it's from a mailing list, I will ignore it.\n");
        _exit(0);			/*report success and exit*/
    }
    if ( inspect_headers("Delivered-To", "Autoresponder" ) != (char *)NULL )
    {
        /*got one of my own messages...*/
        fprintf(stderr,"AUTORESPOND: This message is looping...it has my Delivered-To header.\n");
        _exit(100);			/*hard error*/
    }
    if ( inspect_headers("precedence", "junk" ) != (char *)NULL ||
            inspect_headers("precedence", "bulk" ) != (char *)NULL ||
            inspect_headers("precedence", "list" ) != (char *)NULL )
    {
        fprintf(stderr,"AUTORESPOND: Junk mail received.\n");
        _exit(0); /* don't reply to bulk, junk, or list mail */
    }

    /*check the logs*/
    if(chdir(dir) == -1) {
        fprintf(stderr,"AUTORESPOND: Failed to change into directory.\n");
        _exit(111);
    }

    /*add entry*/
    sprintf(filename,"A%u.%u",getpid(),timer);
    f = fopen(filename,"wb");
    if(f==NULL) {
        fprintf(stderr,"AUTORESPOND: Unable to create file for [%s].",sender);
        _exit(111);
    }
    if(fwrite(sender,1,strlen(sender),f)!=strlen(sender)) {
        fprintf(stderr,"AUTORESPOND: Unable to create file for [%s].",sender);
        fclose(f);
        unlink(filename);
        _exit(111);
    }
    fclose(f);

    /*check if there are too many responses in the logs*/
    dirp = opendir(".");
    count = 0;
    while((direntp = readdir(dirp)) != NULL) {
        if(direntp->d_name[0] != 'A')
            continue;
        ptr = strchr(direntp->d_name,'.');
        if(ptr==NULL)
            continue;
        message_time = strtoul(ptr+1,NULL,10);
        if(message_time < timer-time_message) {
            /*too old..ignore errors on unlink*/
            unlink(direntp->d_name);
        } else {
            address = read_file(direntp->d_name);
            if(address==NULL) {
                /*ignore this?*/
                continue;
            }
            if(strcasecmp(address,sender)==0) {
                count++;
            }
            free(address);
        }
    }
    if(count>num) {
        fprintf(stderr,"AUTORESPOND: too many received from [%s]\n",sender);
        _exit(0); /* don't reply to this message, but allow it to be delivered */
    }

    sprintf(filename,"tmp%u.%u",getpid(),timer);
    f = fopen(filename,"wb");

    fprintf( f, "%sTo: %s\nFrom: %s\nSubject: Re:%s\n%s\n",
             my_delivered_to, sender, rpath, inspect_headers( "Subject", (char *) NULL ), message );

    if ( message_handling == 1 ) {
        fprintf( f, "%s\n\n", "-------- Original Message --------" );
        if ( (content_boundary = get_content_boundary()) == (char *)NULL )
        {
            while ( fgets( buffer, sizeof(buffer), stdin ) != NULL )
            {
                fputs( "> ", f );
                fputs( buffer, f );
            }
        } else
        {
            int content_found = 0;
            while ( fgets( buffer, sizeof(buffer), stdin ) != NULL )
            {
                if ( content_found == 1 )
                {
                    if ( strstr( buffer, content_boundary ) != (char *)NULL )
                        break;
                    fputs( "> ", f );
                    fputs( buffer, f );
                }
                if ( strstr( buffer, content_boundary ) != (char *)NULL )
                {
                    if ( content_found == 1 )
                        break;
                    else
                    {
                        free_headers();
                        read_headers( stdin );
                        if ( inspect_headers("Content-Type", "text/plain" ) != (char *)NULL )
                            content_found = 1;
                        continue;
                    }
                }
            }
        }
    }

    fprintf( f, "\n\n" );

    fclose( f );

    /*send the autoresponse...ignore errors?*/
    send_message(filename,rpath,&sender,1);

    unlink( filename );

    _exit(0);
    return 0;					/*compiler warning squelch*/
}
Beispiel #26
0
int main(int argc, char *argv[]) {
    int server_coid, self_coid, chid, rcvid;
    struct reg_msg msg;

    setvbuf (stdout, NULL, _IOLBF, 0);

    /* look for server */
    server_coid = name_open( RECV_NAME, 0 );
    while( server_coid == -1 )
    {
        sleep(1);
        server_coid = name_open( RECV_NAME, 0 );
    }

    chid = ChannelCreate(0);
    if( -1 == chid)
    {
        perror( PROGNAME "ChannelCreate");
        exit( EXIT_FAILURE );
    }
    self_coid = ConnectAttach( 0, 0, chid, _NTO_SIDE_CHANNEL, 0 );
    if( -1 == self_coid )
    {
        perror( PROGNAME "ConnectAttach");
        exit( EXIT_FAILURE );
    }

    msg.type = REG_MSG;

    /* class: Initialize the sigevent structure (msg.ev) in the message
     * to be sent to the server.
     */

    if (MsgSend( server_coid, &msg, sizeof( msg ), NULL, 0 ) == -1)
    {
        perror(PROGNAME "MsgSend");
        exit( EXIT_FAILURE );
    }

    while( 1 )
    {
        rcvid = MsgReceive( chid, &recv_buf, sizeof(recv_buf), NULL );
        if( -1 == rcvid )
        {
            perror(PROGNAME "MsgReceive");
            continue;
        }
        if ( 0 == rcvid )
        {
            if (MY_PULSE_CODE == recv_buf.pulse.code )
            {
                printf(PROGNAME "got my pulse\n");
            } else
            {
                printf(PROGNAME "got unexpected pulse with code %d\n",
                       recv_buf.pulse.code );
            }
            continue;
        }
        printf(PROGNAME "got unexpected message, type: %d\n", recv_buf.type );
        MsgError( rcvid, ENOSYS );
    }
}
Beispiel #27
0
int
main(int argc, char **argv)
{
	register int cnt, op, i;
	bpf_u_int32 localnet, netmask;
	register char *cp, *infile, *cmdbuf, *device, *RFileName, *WFileName;
	pcap_handler printer;
	struct bpf_program fcode;
	RETSIGTYPE (*oldhandler)(int);
	u_char *pcap_userdata;
	char ebuf[PCAP_ERRBUF_SIZE];

	cnt = -1;
	device = NULL;
	infile = NULL;
	RFileName = NULL;
	WFileName = NULL;
	if ((cp = strrchr(argv[0], '/')) != NULL)
		program_name = cp + 1;
	else
		program_name = argv[0];

	if (abort_on_misalignment(ebuf) < 0)
		error("%s", ebuf);

	opterr = 0;
	while (
	    (op = getopt(argc, argv, "ac:defF:i:lnNOpqr:s:StT:vw:xY")) != EOF)
		switch (op) {

		case 'a':
			++aflag;
			break;

		case 'c':
			cnt = atoi(optarg);
			if (cnt <= 0)
				error("invalid packet count %s", optarg);
			break;

		case 'd':
			++dflag;
			break;

		case 'e':
			++eflag;
			break;

		case 'f':
			++fflag;
			break;

		case 'F':
			infile = optarg;
			break;

		case 'i':
			device = optarg;
			break;

		case 'l':
#ifdef HAVE_SETLINEBUF
			setlinebuf(stdout);
#else
			setvbuf(stdout, NULL, _IOLBF, 0);
#endif
			break;

		case 'n':
			++nflag;
			break;

		case 'N':
			++Nflag;
			break;

		case 'O':
			Oflag = 0;
			break;

		case 'p':
			++pflag;
			break;

		case 'q':
			++qflag;
			break;

		case 'r':
			RFileName = optarg;
			break;

		case 's':
			snaplen = atoi(optarg);
			if (snaplen <= 0)
				error("invalid snaplen %s", optarg);
			break;

		case 'S':
			++Sflag;
			break;

		case 't':
			--tflag;
			break;

		case 'T':
			if (strcasecmp(optarg, "vat") == 0)
				packettype = PT_VAT;
			else if (strcasecmp(optarg, "wb") == 0)
				packettype = PT_WB;
			else if (strcasecmp(optarg, "rpc") == 0)
				packettype = PT_RPC;
			else if (strcasecmp(optarg, "rtp") == 0)
				packettype = PT_RTP;
			else if (strcasecmp(optarg, "rtcp") == 0)
				packettype = PT_RTCP;
			else
				error("unknown packet type `%s'", optarg);
			break;

		case 'v':
			++vflag;
			break;

		case 'w':
			WFileName = optarg;
			break;
#ifdef YYDEBUG
		case 'Y':
			{
			/* Undocumented flag */
			extern int yydebug;
			yydebug = 1;
			}
			break;
#endif
		case 'x':
			++xflag;
			break;

		default:
			usage();
			/* NOTREACHED */
		}

	if (aflag && nflag)
		error("-a and -n options are incompatible");

	if (tflag > 0)
		thiszone = gmt2local(0);

	if (RFileName != NULL) {
		/*
		 * We don't need network access, so set it back to the user id.
		 * Also, this prevents the user from reading anyone's
		 * trace file.
		 */
		setuid(getuid());

		pd = pcap_open_offline(RFileName, ebuf);
		if (pd == NULL)
			error("%s", ebuf);
		localnet = 0;
		netmask = 0;
		if (fflag != 0)
			error("-f and -r options are incompatible");
	} else {
		if (device == NULL) {
			device = pcap_lookupdev(ebuf);
			if (device == NULL)
				error("%s", ebuf);
		}
		pd = pcap_open_live(device, snaplen, !pflag, 1000, ebuf);
		if (pd == NULL)
			error("%s", ebuf);
		i = pcap_snapshot(pd);
		if (snaplen < i) {
			warning("snaplen raised from %d to %d", snaplen, i);
			snaplen = i;
		}
		if (pcap_lookupnet(device, &localnet, &netmask, ebuf) < 0) {
			localnet = 0;
			netmask = 0;
			warning("%s", ebuf);
		}
		/*
		 * Let user own process after socket has been opened.
		 */
		setuid(getuid());
	}
	if (infile)
		cmdbuf = read_infile(infile);
	else
		cmdbuf = copy_argv(&argv[optind]);

	if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0)
		error("%s", pcap_geterr(pd));
	if (dflag) {
		bpf_dump(&fcode, dflag);
		exit(0);
	}
	init_addrtoname(localnet, netmask);

	(void)setsignal(SIGTERM, cleanup);
	(void)setsignal(SIGINT, cleanup);
	/* Cooperate with nohup(1) */
	if ((oldhandler = setsignal(SIGHUP, cleanup)) != SIG_DFL)
		(void)setsignal(SIGHUP, oldhandler);

	if (pcap_setfilter(pd, &fcode) < 0)
		error("%s", pcap_geterr(pd));
	if (WFileName) {
		pcap_dumper_t *p = pcap_dump_open(pd, WFileName);
		if (p == NULL)
			error("%s", pcap_geterr(pd));
		printer = pcap_dump;
		pcap_userdata = (u_char *)p;
	} else {
		printer = lookup_printer(pcap_datalink(pd));
		pcap_userdata = 0;
	}
	if (RFileName == NULL) {
		(void)fprintf(stderr, "%s: listening on %s\n",
		    program_name, device);
		(void)fflush(stderr);
	}
	if (pcap_loop(pd, cnt, printer, pcap_userdata) < 0) {
		(void)fprintf(stderr, "%s: pcap_loop: %s\n",
		    program_name, pcap_geterr(pd));
		exit(1);
	}
	pcap_close(pd);
	exit(0);
}
int main(int argc, char *argv[]) {
  unsigned char *pkt = NULL, *pkt_bak, *mcast6, *someaddr6 = NULL;
  unsigned char *dst6, *src6 = NULL, *mac = NULL, *routers[2], string[64] = "icmp6 and dst ";
  int rawmode = 0, test_start = 0, fragment = 0, alert = 0, sroute = 0;
  int do_type = DO_PING, do_alive = 1, hopbyhop = 0, destination = 0, jumbo = 0;
  int pkt_len = 0, offset = 0, test_current = 0, i, j, k, do_fuzz = 1, test_ptr = 0;
  int test_end = TEST_MAX, ping = NEVER, frag_offset = 0, header = 0, no_send = 1;
  int test_pos = 0, test_cnt = 0, do_it, extend = 0, mtu = 1500, size = 64, wait = 0;
  char *interface, fuzzbuf[256], *srcmac, *dns, *route6, *real_dst6 = NULL;
  unsigned char buf[256], buf2[100], buf3[16];
  unsigned short int *sip;
  pcap_t *p;
  thc_ipv6_hdr *hdr;

  if (argc < 3 || strncmp(argv[1], "-h", 2) == 0)
    help(argv[0]);

  while ((i = getopt(argc, argv, "123456789rxt:T:p:FSDHRIJan:")) >= 0) {
    switch (i) {
    case '1':
      do_type = DO_PING;
      break;
    case '2':
      do_type = DO_NEIGHSOL;
      break;
    case '3':
      do_type = DO_NEIGHADV;
      break;
    case '4':
      do_type = DO_RA;
      break;
    case '5':
      do_type = DO_MLD_REP;
      break;
    case '6':
      do_type = DO_MLD_DONE;
      break;
    case '7':
      do_type = DO_MLD_QUERY;
      wait = 0xff0000;
      break;
    case '8':
      do_type = DO_MLD2_REPORT;
      break;
    case '9':
      do_type = DO_MLD2_QUERY;
      wait = 0xff0000;
      break;
    case 'r':
      thc_ipv6_rawmode(1);
      rawmode = 1;
      test_pos -= 14;
      offset -= 14;
      break;
    case 't':
      test_start = atoi(optarg);
      break;
    case 'T':
      test_end = test_start = atoi(optarg);
      break;
    case 'p':
      ping = atoi(optarg);
      break;
    case 'a':
      do_alive = 0;
      break;
    case 'S':
      sroute = 1;
      break;
    case 'n':
      no_send = atoi(optarg);
      break;
    case 'F':
      fragment = 1;
      break;
    case 'R':
      alert = 1;
      break;
    case 'D':
      destination = 1;
      break;
    case 'H':
      hopbyhop = 1;
      break;
    case 'J':
      jumbo = 1;
      break;
    case 'I':
      header = 1;
      break;
    case 'x':
      extend = 1;
      break;
    }
  }
  if (argc - optind < 2) {
    fprintf(stderr, "ERROR: not enough options, interface and target address are required!\n");
    exit(-1);
  }
  interface = argv[optind];
  if (rawmode == 0 && (srcmac = thc_get_own_mac(interface)) == NULL) {
    fprintf(stderr, "ERROR: %s is not a valid interface which has a MAC, use raw mode?\n", interface);
    exit(-1);
  }
  if (no_send < 1) {
    fprintf(stderr, "ERROR: -n number must be between one and 2 billion\n");
    exit(-1);
  }
  if (do_type != DO_PING) {
    mcast6 = thc_resolve6(argv[optind + 1]);
    if (do_type == DO_NEIGHSOL) {
      dst6 = thc_resolve6("ff02::0001:ff00:0000");
      memcpy(dst6 + 13, mcast6 + 13, 3);
    } else
      dst6 = thc_resolve6("ff02::1");
  } else {
    dst6 = thc_resolve6(argv[optind + 1]);
  }
  if (argv[optind + 1] != NULL)
    real_dst6 = thc_resolve6(argv[optind + 1]);

  if (interface == NULL || argv[optind + 1] == NULL) {
    printf("Error: interface and target-ipv6-address are mandatory command line options\n");
    exit(-1);
  }
  if (ping < 1 || test_end < test_start) {
    printf("dont f**k up the command line options!\n");
    exit(-1);
  }
  if (argv[optind + 2] != NULL)
    someaddr6 = thc_resolve6(argv[optind + 2]);
  if (argc - optind > 3) {
    printf("Error: too many command line options\n");
    exit(-1);
  }
  if ((mac = thc_get_mac(interface, src6, dst6)) == NULL) {
    fprintf(stderr, "ERROR: Can not resolve mac address for %s\n", argv[2]);
    exit(-1);
  }
  if (rawmode)
    srcmac = mac;

  if (do_type == DO_PING)
    src6 = thc_get_own_ipv6(interface, dst6, PREFER_GLOBAL);
  else
    src6 = thc_get_own_ipv6(interface, dst6, PREFER_LINK);
  strcat(string, thc_ipv62notation(src6));
  if (sroute) {
    if (someaddr6 != NULL)
      routers[0] = someaddr6;
    else
      routers[0] = dst6;
    routers[1] = NULL;
  }
  setvbuf(stdout, NULL, _IONBF, 0);
  memset(buf, 0, sizeof(buf));
  memset(buf2, 0, sizeof(buf2));
  dns = thc_resolve6("FF02::FB");
  route6 = thc_resolve6("2a01::");

  if ((p = thc_pcap_init(interface, string)) == NULL) {
    fprintf(stderr, "Error: could not capture on interface %s with string %s\n", interface, string);
    exit(-1);
  }
  // ping before to check if it works
  if (do_alive)
    if (check_alive(p, interface, src6, real_dst6) == 0) {
      fprintf(stderr, "Error: target %s is not alive via direct ping6!\n", argv[optind + 1]);
      exit(-1);
    }
  // generate basic packet
  strcpy(fuzzbuf, fuzztype_ether);
  if ((pkt = thc_create_ipv6(interface, PREFER_GLOBAL, &pkt_len, src6, dst6, 0, 0, 0, 0, 0)) == NULL)
    return -1;
  if (header)
    strcat(fuzzbuf, fuzztype_ip6);
  else
    strcat(fuzzbuf, fuzztype_ip6no);

  if (alert || hopbyhop || jumbo) {
    memset(buf2, 0, sizeof(buf2));
    i = 0;

    if (alert) {
      buf2[i++] = 5;
      buf2[i++] = 2;
      i += 2;
      strcat(fuzzbuf, ".F.F");
    }

    if (jumbo) {
      buf2[i++] = 0xc2;
      buf2[i++] = 4;
      buf2[i++] = 'J';          // lookup code
      buf2[i++] = 'J';
      buf2[i++] = 'J';
      buf2[i++] = 'J';
      strcat(fuzzbuf, ".FBBBB");
    }

    if (hopbyhop) {
      memset(buf3, 0, sizeof(buf3));
      buf3[0] = 'X';
      buf3[1] = '.';
      for (j = 0; j < 10; j++) {
        buf2[i++] = 1;          // PadN, length
        buf2[i++] = j;
        if (j > 0) {
          memset(buf2 + i, 0xaa, j);
          buf3[2 + j] = '.';
          i += j;
        }
        strcat(fuzzbuf, buf3);  // always: X... for every new option
      }
    }

    if (thc_add_hdr_hopbyhop(pkt, &pkt_len, buf2, i) < 0)
      return -1;

    i += 2;
    if (i % 8 > 0)
      i = ((i / 8) + 1) * 8;

    offset += i;
  }

  if (sroute) {
    if (thc_add_hdr_route(pkt, &pkt_len, routers, 1) < 0)
      return -1;
    else {
      strcat(fuzzbuf, "FFFFBBBB................");
      offset += 24;
    }
  }

  if (fragment) {
    frag_offset = offset;
    if (thc_add_hdr_fragment(pkt, &pkt_len, 0, 0, 0) < 0)
      return -1;
    else {
      strcat(fuzzbuf, "FFWW..");
      offset += 8;
    }
  }

  if (destination) {
    memset(buf2, 0, sizeof(buf2));
    memset(buf3, 0, sizeof(buf3));
    buf3[0] = 'X';
    buf3[1] = '.';
    i = 0;
    for (j = 0; j < 10; j++) {
      buf2[i++] = 1;            // PadN, length
      buf2[i++] = j;
      if (j > 0) {
        memset(buf2 + i, 0xaa, j);
        buf3[2 + j] = '.';
        i += j;
      }
      strcat(fuzzbuf, buf3);    // always: X... for every new option
    }

    if (thc_add_hdr_dst(pkt, &pkt_len, buf2, i) < 0)
      return -1;

    i += 2;
    if (i % 8 > 0)
      i = ((i / 8) + 1) * 8;

    offset += i;
  }

  memset(buf, 0, sizeof(buf));
  if (header)
    strcat(fuzzbuf, fuzztype_icmp6);
  else
    strcat(fuzzbuf, fuzztype_icmp6no);
  switch (do_type) {
  case DO_PING:
    if (thc_add_icmp6(pkt, &pkt_len, ICMP6_PINGREQUEST, 0, test_current, (unsigned char *) &buf, 16, 0) < 0)
      return -1;
    strcat(fuzzbuf, fuzztype_icmp6ping);
    break;

  case DO_NEIGHSOL:
    if (someaddr6 != NULL)
      memcpy(buf, someaddr6, 16);
    else
      memcpy(buf, mcast6, 16);
    buf[16] = 1;
    buf[17] = 1;
    memcpy(buf + 18, srcmac, 6);
    if (thc_add_icmp6(pkt, &pkt_len, ICMP6_NEIGHBORSOL, 0, 0, (unsigned char *) &buf, 24, 0) < 0)
      return -1;
    strcat(fuzzbuf, fuzztype_icmp6ns);
    break;

  case DO_NEIGHADV:
    if (someaddr6 != NULL)
      memcpy(buf, someaddr6, 16);
    else
      memcpy(buf, src6, 16);
    buf[16] = 2;
    buf[17] = 1;
    memcpy(buf + 18, srcmac, 6);
    if (thc_add_icmp6(pkt, &pkt_len, ICMP6_NEIGHBORADV, 0, 0xe0000000, (unsigned char *) &buf, 24, 0) < 0)
      return -1;
    strcat(fuzzbuf, fuzztype_icmp6na);
    break;

  case DO_RA:
    //  buf[3] = 250; // 0-3: reachable timer
    buf[6] = 4;                 // 4-7: retrans timer
    // option mtu
    buf[8] = 5;
    buf[9] = 1;
    buf[12] = mtu / 16777216;

    buf[14] = (mtu % 65536) / 256;
    buf[15] = mtu % 256;
    // option prefix
    buf[16] = 3;
    buf[17] = 4;
    buf[18] = size;             // prefix length
    buf[19] = 128 + 64;
    memset(&buf[20], 17, 4);
    memset(&buf[24], 4, 4);
    if (someaddr6 != NULL)
      memcpy(&buf[32], someaddr6, 16);
    else
      memcpy(&buf[32], route6, 16);

    i = 48;
    // mac address option
    buf[i++] = 1;
    buf[i++] = 1;
    memcpy(buf + i, srcmac, 6);
    i += 6;

    // default route routing option
    buf[i++] = 0x18;            // routing entry option type
    buf[i++] = 0x03;            // length 3 == 24 bytes
    buf[i++] = 0x00;            // prefix length
    buf[i++] = 0x08;            // priority, highest of course
    i += 2;                     // 52-53 unknown
    buf[i++] = 0x11;            // lifetime, word
    buf[i++] = 0x11;            // lifetime, word
    i += 16;                    // 56-71 address, all zeros for default

    // dns option
    buf[i++] = 0x19;            // dns option type
    buf[i++] = 0x03;            // length
    i += 2;                     // 74-75 reserved
    memset(buf + i, 1, 4);      // validity time
    i += 4;
    if (someaddr6 != NULL)
      memcpy(buf + i, someaddr6, 16);   // dns server
    else
      memcpy(buf + i, dns, 16); // dns server
    i += 16;

    if (thc_add_icmp6(pkt, &pkt_len, ICMP6_ROUTERADV, 0, 0xff080800, buf, i, 0) < 0)
      return -1;
    strcat(fuzzbuf, fuzztype_icmp6ra);
    break;

  case DO_MLD_QUERY:
  case DO_MLD_DONE:
  case DO_MLD_REP:
    buf[0] = 0xff;
    buf[1] = 0x02;
    buf[15] = 0x05;
    if (someaddr6 != NULL)
      memcpy(buf, someaddr6, 16);
    if (thc_add_icmp6(pkt, &pkt_len, do_type, 0, wait, buf, 16, 0) < 0)
      return -1;
    strcat(fuzzbuf, fuzztype_icmp6mld);
    break;
  case DO_MLD2_QUERY:
    buf[0] = 0xff;
    buf[1] = 0x02;
    buf[15] = 0x05;
    if (someaddr6 != NULL)
      memcpy(buf, someaddr6, 16);
    buf[16] = 7;
    buf[17] = 120;
    buf[19] = 3;
    memcpy(buf + 20, dst6, 16);
    memcpy(buf + 36, buf, 16);
    if (thc_add_icmp6(pkt, &pkt_len, DO_MLD_QUERY, 0, wait, buf, 68, 0) < 0)
      return -1;
    strcat(fuzzbuf, fuzztype_icmp6mld2que);
    break;
  case DO_MLD2_REPORT:
    for (i = 0; i < 3; i++) {
      buf[0 + 68 * i] = 1 + i * 2 - i / 2;      //include new++, generates 1, 3 and 4
      buf[3 + 68 * i] = 3;      //3 sources
      buf[4 + 68 * i] = 0xff;
      buf[5 + 68 * i] = 0x02;
      buf[18 + 68 * i] = 0x82 + i % 256;
      buf[19 + 68 * i] = 0xff;
      memcpy(buf + 20 + 68 * i, src6, 16);
      buf[36 + 68 * i] = 0xfe;
      buf[37 + 68 * i] = 0x80;
      buf[46 + 68 * i] = 0xf0;
      if (someaddr6 != NULL)
        memcpy(buf + 52 + 68 * i, someaddr6, 16);
    }

    if (thc_add_icmp6(pkt, &pkt_len, do_type, 0, 3, buf, 208, 0) < 0)
      return -1;
    strcat(fuzzbuf, fuzztype_icmp6mld2rep);
    break;

  default:
    fprintf(stderr, "ERROR: Mode not implemented yet!\n");
    exit(-1);
  }

  if (thc_generate_pkt(interface, srcmac, mac, pkt, &pkt_len) < 0)
    return -1;
  hdr = (thc_ipv6_hdr *) pkt;

  if (jumbo) {
    i = 0;
    j = 1;
    while (i < hdr->pkt_len + 4 && j) {
      if (hdr->pkt[i] == 'J')
        if (memcmp(&hdr->pkt[i], "JJJJ", 4) == 0)
          j = 0;
      i++;
    }
    if (j) {
      fprintf(stderr, "ERROR: fuckup, cant find my own marker?!\n");
      exit(-1);
    } else
      i--;
    hdr->pkt[i] = 0;
    hdr->pkt[i + 1] = 0;
    hdr->pkt[i + 2] = hdr->pkt[4 + 14 - 14 * rawmode];
    hdr->pkt[i + 3] = hdr->pkt[5 + 14 - 14 * rawmode];
    hdr->pkt[4 + 14 - 14 * rawmode] = 0;
    hdr->pkt[5 + 14 - 14 * rawmode] = 0;
  }

  if (extend)
    for (i = 0; i < strlen(fuzzbuf); i++)
      if (fuzzbuf[i] == 'B' || fuzzbuf[i] == 'F')
        fuzzbuf[i] = 'X';

  // backup of generated packet
  pkt_bak = malloc(hdr->pkt_len);
  memcpy(pkt_bak, hdr->pkt, hdr->pkt_len);

  printf("Fuzzing packet, starting at fuzz case %d, ending at fuzz case %d, every packet sent denoted by a dot:\n", test_start, test_end);
//printf("buf(%d): %s\n", strlen(fuzzbuf), fuzzbuf);
  while (do_fuzz) {
    if (test_cnt == 0)
      while (fuzzbuf[test_ptr] == '.') {
        test_ptr++;
        test_pos++;
      }

    if (fuzzbuf[test_ptr] == 0)
      do_fuzz = 0;

    test_cnt++;
    do_it = 1;

//printf("[%s] pos[%d]=%c -> %d | pkt[%d] | %d (%d=>%d)| ", /*fuzzbuf*/"", test_ptr, fuzzbuf[test_ptr], test_cnt, test_pos, test_current, test_start, test_end);

    switch (fuzzbuf[test_ptr]) {
    case 0:
      break;
    case 'X':
      if (test_cnt <= COUNT_EXTEND) {
        if (pkt_bak[test_pos] != extends[test_cnt - 1])
          hdr->pkt[test_pos] = extends[test_cnt - 1];
        else
          do_it = 0;
      } else {
        test_cnt = 0;
        test_ptr++;
        test_pos++;
      }
      break;
    case 'B':
      if (test_cnt <= COUNT_BYTE) {
        if (pkt_bak[test_pos] != bytes[test_cnt - 1])
          hdr->pkt[test_pos] = bytes[test_cnt - 1];
        else
          do_it = 0;
      } else {
        i = 0;
        while (i < COUNT_BYTE && do_it) {
          if (bytes[i] == pkt_bak[test_pos])
            do_it = 0;
          i++;
        }
        if (do_it)
          hdr->pkt[test_pos] = hdr->pkt[test_pos] ^ xors[test_cnt - COUNT_BYTE - 1];
      }
      if (test_cnt == COUNT_BYTE + COUNT_XOR) {
        test_cnt = 0;
        test_ptr++;
        test_pos++;
      }
      break;
    case 'F':
      if (test_cnt <= COUNT_FLAG) {
        if (pkt_bak[test_pos] != flags[test_cnt - 1])
          hdr->pkt[test_pos] = flags[test_cnt - 1];
        else
          do_it = 0;
      } else {
        i = 0;
        while (i < COUNT_FLAG && do_it) {
          if (bytes[i] == pkt_bak[test_pos])    // yes, bytes[] is the right one even for flags
            do_it = 0;
          i++;
        }
        if (do_it)
          hdr->pkt[test_pos] = hdr->pkt[test_pos] ^ xors[test_cnt - COUNT_BYTE - 1];
      }
      if (test_cnt == COUNT_FLAG + COUNT_XOR) {
        test_cnt = 0;
        test_ptr++;
        test_pos++;
      }
      break;
    case 'W':
      sip = (unsigned short int *) &pkt_bak[test_pos];
      if (test_cnt <= COUNT_WORD) {
        if (*sip != words[test_cnt - 1])
          memcpy((char *) &hdr->pkt[test_pos], (char *) &words[test_cnt - 1], 2);
        else
          do_it = 0;
      } else {
        i = 0;
        while (i < COUNT_WORD && do_it) {
          if (words[i] == *sip)
            do_it = 0;
          i++;
        }
        if (do_it) {
          i = *sip ^ xors[test_cnt - COUNT_WORD - 1];
          sip = (unsigned short int *) &hdr->pkt[test_pos];
          *sip = i % 65536;
        }
      }
      if (test_cnt == COUNT_WORD + COUNT_XOR) {
        test_cnt = 0;
        test_ptr++;
        test_pos += 2;
      }
      break;
    default:
      fprintf(stderr, "This character should not be in the fuzz string, shoot the programmer: %c(%d) position %d string %s\n", fuzzbuf[test_ptr], fuzzbuf[test_ptr], test_ptr,
              fuzzbuf);
      exit(-1);
      break;
    }

    if (do_it && do_fuzz) {
      if (test_current >= test_start && test_current <= test_end && do_fuzz) {
        // fill icmp id+seq and unique buffer with test case number
        if (fragment)
          memcpy(hdr->pkt + frag_offset + 58, (char *) &test_current, 4);
        switch (do_type) {
        case DO_PING:
          for (i = 0; i < 4 + 1; i++)
            memcpy(hdr->pkt + offset + 58 + i * 4, (char *) &test_current, 4);
          break;
        case DO_NEIGHSOL:
        case DO_NEIGHADV:
          break;                // do nothing for these
        case DO_RA:
          memcpy(hdr->pkt + offset + 0x62, (char *) &test_current, 4);  // prefix update
          memcpy(hdr->pkt + offset + 0x7e, hdr->pkt + offset + 0x5e, 16);       // routing update
          if (rawmode == 0)
            memcpy(hdr->pkt + 8, (char *) &test_current, 4);    // srcmac update
          memcpy(hdr->pkt + offset + 0x72, (char *) &test_current, 4);  // srcmac update
          memcpy(hdr->pkt + 0x10 + 14 - 14 * rawmode, (char *) &test_current, 4);       // srcip update
          memcpy(hdr->original_src, hdr->pkt + 8 + 14 - 14 * rawmode, 16);      // srcip update for checksum
          break;
        case DO_MLD_QUERY:
        case DO_MLD_DONE:
        case DO_MLD_REP:
        case DO_MLD2_QUERY:
          memcpy(hdr->pkt + offset + 0x4a, (char *) &test_current, 4);
          break;
        case DO_MLD2_REPORT:   //??? XXX TODO CHECK
          memcpy(hdr->pkt + offset + 0x4d, (char *) &test_current, 4);
          memcpy(hdr->pkt + offset + 0x4d + 68, (char *) &test_current, 4);
          memcpy(hdr->pkt + offset + 0x4d + 136, (char *) &test_current, 4);
          break;
        default:
          fprintf(stderr, "ERROR!!!\n");
          exit(-1);
        }

        // regenerate checksum
        if (do_type == do_type) {       // maybe for later non-icmp stuff
          hdr->pkt[offset + 56] = 0;
          hdr->pkt[offset + 57] = 0;
          i = checksum_pseudo_header(hdr->original_src, hdr->final_dst, NXT_ICMP6, &hdr->pkt[offset + 54], hdr->pkt_len - offset - 54);
          hdr->pkt[offset + 56] = i / 256;
          hdr->pkt[offset + 57] = i % 256;
        }
        // send packet
        for (k = 0; k < no_send; k++) {
          if (thc_send_pkt(interface, pkt, &pkt_len) < 0)
            return -1;
          usleep(1);
        }
        printf(".");
        usleep(250);
        // if ping, check ping again
        if ((test_current - test_start) % ping == 0 && test_current != 0 && test_start != test_current)
          if (check_alive(p, interface, src6, real_dst6) == 0) {
            i = ((((test_current - test_start) / ping) - 1) * ping) + test_start + 1;
            printf("\nResult: target %s crashed during fuzzing, offending test case no. could be %d to %d\n", argv[optind + 1], i < 0 ? 0 : i, test_current);
            exit(-1);
          }
      }
//else printf("NOT SENT - NOT IN TEST LIST\n");
      // reset to basic packet
      memcpy(hdr->pkt, pkt_bak, hdr->pkt_len);
      test_current++;
    }
//else printf("NOT SENT!\n");
  }

  printf("\n");
  // ping afterwards to check if it worked
  if (do_alive) {
    if (check_alive(p, interface, src6, real_dst6) == 0)
      printf("Result: target %s is NOT alive via direct ping6 - good work! (position: %d)\n", argv[optind + 1], test_pos);
    else
      printf("Result: target %s is still alive via direct ping6, better luck next time.\n", argv[optind + 1]);
  }

  thc_pcap_close(p);
  return 0;
}
Beispiel #29
0
int main(int argc, char **argv, char **envp)
{
	uint64_t module_count;
	proc_module_info_t *buffer = NULL;
	struct lpar_info_format1_t  lpar_data1;
	struct utsname my_uname;
	int rc;
	int i;
	char *progname;
	char iobuf[BUFSIZ];

	setvbuf(stdout, iobuf, _IOFBF, sizeof(iobuf));

	progname=(char*)strdup((const char*)basename(argv[0]));
	if (!progname)
	{
		fprintf(stderr, "FATAL: Buffer allocation failed at (%s:%d): %s, error code %d\n",
		 __FILE__, __LINE__, strerror(errno), errno);
		return EXIT_FAILURE;
	}

	uname(&my_uname);

	/* Retrieve the total count of modules on the system */
	rc = lpar_get_info(NUM_PROC_MODULE_TYPES, &module_count, sizeof(uint64_t));
			 
	if (rc)
	{
		fprintf(stderr, "%s: lpar_get_info(NUM_PROC_MODULES_TYPES, ...) failed at (%s:%d):  %s, error code %d\n",
		 progname, __FILE__, __LINE__, strerror(errno), errno);
		return EXIT_FAILURE;
	}
	             
	/* Allocate buffer of exact size to accomodate module information */
	buffer = malloc(module_count * sizeof(proc_module_info_t));
	     
	if (!buffer)
	{
		fprintf(stderr, "%s: Buffer allocation failed at (%s:%d): %s, error code %d\n",
		 progname, __FILE__, __LINE__, strerror(errno), errno);
		return EXIT_FAILURE;
	}
	
	rc = lpar_get_info(PROC_MODULE_INFO, buffer, (module_count * sizeof(proc_module_info_t)));
	
	if (rc)
	{
		fprintf(stderr, "%s: lpar_get_info(PROC_MODULE_INFO, ...) failed at (%s:%d):  %s, error code %d\n",
		 progname, __FILE__, __LINE__, strerror(errno), errno);
		return EXIT_FAILURE;
	}
	
	/* Retrieve the static LPAR structure */
	rc = lpar_get_info(LPAR_INFO_FORMAT1, &lpar_data1, sizeof(lpar_data1));
			 
	if (rc)
	{
		fprintf(stderr, "%s: lpar_get_info(LPAR_INFO_FORMAT1, ...) failed at (%s:%d):  %s, error code %d\n",
		 progname, __FILE__, __LINE__, strerror(errno), errno);
		return EXIT_FAILURE;
	}


	/*  If rc is 0, then buffer contains an array of proc_module_info_t
	 *  structures with module_count elements.  For an element of 
	 *  index i:
	 *       
	 *      buffer[i].nsockets is the total number of sockets
	 *      buffer[i].nchips   is the number of chips per socket		 
	 *      buffer[i].ncores   is the number of cores per chip
	 */
	 
	printf(
	  "Nodename     %-." QUOTE(SYS_NMLN) "s\n"
	  "LPAR         %-." QUOTE(LPAR_NAME_LEN1) "s\n"
	  "Machine      %-." QUOTE(SYS_NMLN) "s\n"
	  "Sysname      %-." QUOTE(SYS_NMLN) "s\n"
	  "Version      %-." QUOTE(SYS_NMLN) "s\n"
	  "Release      %-." QUOTE(SYS_NMLN) "s\n"
	  "SMT threads  %hu\n",
	  &(my_uname.nodename),
	  &(lpar_data1.lpar_name),
	  &(my_uname.machine),
	  &(my_uname.sysname),
	  &(my_uname.version),
	  &(my_uname.release),
	  lpar_data1.smt_threads);

	for (i=0 ; i < module_count ; i++)
	{
		printf(
		  "Sockets      %d\n"
		  "Chips/Socket %d\n"
		  "Cores/Chip   %d\n"
		  "Cores/Socket %d\n",
		  buffer[i].nsockets,
		  buffer[i].nchips,
		  buffer[i].ncores,
		  buffer[i].ncores * buffer[i].nchips);
	}
	fflush(stdout);
	return 0;
}
Beispiel #30
-1
/*! \brief
* creates a FILE * from the fd passed by the accept thread.
* This operation is potentially expensive (certificate verification),
* so we do it in the child thread context.
*
* \note must decrement ref count before returning NULL on error
*/
static void *handle_tcptls_connection(void *data)
{
	struct ast_tcptls_session_instance *tcptls_session = data;
#ifdef DO_SSL
	int (*ssl_setup)(SSL *) = (tcptls_session->client) ? SSL_connect : SSL_accept;
	int ret;
	char err[256];
#endif

	/*
	* open a FILE * as appropriate.
	*/
	if (!tcptls_session->parent->tls_cfg) {
		if ((tcptls_session->f = fdopen(tcptls_session->fd, "w+"))) {
			if(setvbuf(tcptls_session->f, NULL, _IONBF, 0)) {
				ast_tcptls_close_session_file(tcptls_session);
			}
		}
	}
#ifdef DO_SSL
	else if ( (tcptls_session->ssl = SSL_new(tcptls_session->parent->tls_cfg->ssl_ctx)) ) {
		SSL_set_fd(tcptls_session->ssl, tcptls_session->fd);
		if ((ret = ssl_setup(tcptls_session->ssl)) <= 0) {
			ast_verb(2, "Problem setting up ssl connection: %s\n", ERR_error_string(ERR_get_error(), err));
		} else {
#if defined(HAVE_FUNOPEN)	/* the BSD interface */
			tcptls_session->f = funopen(tcptls_session->ssl, ssl_read, ssl_write, NULL, ssl_close);

#elif defined(HAVE_FOPENCOOKIE)	/* the glibc/linux interface */
			static const cookie_io_functions_t cookie_funcs = {
				ssl_read, ssl_write, NULL, ssl_close
			};
			tcptls_session->f = fopencookie(tcptls_session->ssl, "w+", cookie_funcs);
#else
			/* could add other methods here */
			ast_debug(2, "no tcptls_session->f methods attempted!\n");
#endif
			if ((tcptls_session->client && !ast_test_flag(&tcptls_session->parent->tls_cfg->flags, AST_SSL_DONT_VERIFY_SERVER))
				|| (!tcptls_session->client && ast_test_flag(&tcptls_session->parent->tls_cfg->flags, AST_SSL_VERIFY_CLIENT))) {
				X509 *peer;
				long res;
				peer = SSL_get_peer_certificate(tcptls_session->ssl);
				if (!peer)
					ast_log(LOG_WARNING, "No peer SSL certificate\n");
				res = SSL_get_verify_result(tcptls_session->ssl);
				if (res != X509_V_OK)
					ast_log(LOG_ERROR, "Certificate did not verify: %s\n", X509_verify_cert_error_string(res));
				if (!ast_test_flag(&tcptls_session->parent->tls_cfg->flags, AST_SSL_IGNORE_COMMON_NAME)) {
					ASN1_STRING *str;
					unsigned char *str2;
					X509_NAME *name = X509_get_subject_name(peer);
					int pos = -1;
					int found = 0;

					for (;;) {
						/* Walk the certificate to check all available "Common Name" */
						/* XXX Probably should do a gethostbyname on the hostname and compare that as well */
						pos = X509_NAME_get_index_by_NID(name, NID_commonName, pos);
						if (pos < 0)
							break;
						str = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name, pos));
						ASN1_STRING_to_UTF8(&str2, str);
						if (str2) {
							if (!strcasecmp(tcptls_session->parent->hostname, (char *) str2))
								found = 1;
							ast_debug(3, "SSL Common Name compare s1='%s' s2='%s'\n", tcptls_session->parent->hostname, str2);
							OPENSSL_free(str2);
						}
						if (found)
							break;
					}
					if (!found) {
						ast_log(LOG_ERROR, "Certificate common name did not match (%s)\n", tcptls_session->parent->hostname);
						if (peer) {
							X509_free(peer);
						}
						ast_tcptls_close_session_file(tcptls_session);
						ao2_ref(tcptls_session, -1);
						return NULL;
					}
				}
				if (peer)
					X509_free(peer);
			}
		}
		if (!tcptls_session->f)	/* no success opening descriptor stacking */
			SSL_free(tcptls_session->ssl);
   }
#endif /* DO_SSL */

	if (!tcptls_session->f) {
		ast_tcptls_close_session_file(tcptls_session);
		ast_log(LOG_WARNING, "FILE * open failed!\n");
#ifndef DO_SSL
		if (tcptls_session->parent->tls_cfg) {
			ast_log(LOG_WARNING, "Attempted a TLS connection without OpenSSL support.  This will not work!\n");
		}
#endif
		ao2_ref(tcptls_session, -1);
		return NULL;
	}

	if (tcptls_session->parent->worker_fn) {
		return tcptls_session->parent->worker_fn(tcptls_session);
	} else {
		return tcptls_session;
	}
}