Пример #1
0
/* Warning: RRD_create will overwrite a RRdb if it already exists */
static int
RRD_create( char *rrd, int summary, unsigned int step, 
            unsigned int process_time, ganglia_slope_t slope)
{
   const char *data_source_type = "GAUGE";
   char *argv[128];
   int  argc=0;
   int heartbeat;
   char s[16], start[64];
   char sum[64];
   char num[64];
   int i;

   /* Our heartbeat is twice the step interval. */
   heartbeat = 8*step;

   switch( slope) {
   case GANGLIA_SLOPE_POSITIVE:
     data_source_type = "COUNTER";
     break;

   case GANGLIA_SLOPE_ZERO:
   case GANGLIA_SLOPE_NEGATIVE:
   case GANGLIA_SLOPE_BOTH:
   case GANGLIA_SLOPE_UNSPECIFIED:
     data_source_type = "GAUGE";
     break;
   }

   argv[argc++] = "dummy";
   argv[argc++] = rrd;
   argv[argc++] = "--step";
   sprintf(s, "%u", step);
   argv[argc++] = s;
   argv[argc++] = "--start";
   sprintf(start, "%u", process_time-1);
   argv[argc++] = start;
   sprintf(sum,"DS:sum:%s:%d:U:U",
           data_source_type,
           heartbeat);
   argv[argc++] = sum;
   if (summary) {
      sprintf(num,"DS:num:%s:%d:U:U", 
              data_source_type,
              heartbeat);
      argv[argc++] = num;
   }

   for(i = 0; i< gmetad_config.num_RRAs; i++)
     {
       argv[argc++] = gmetad_config.RRAs[i];
     }
#if 0
   /* Read in or defaulted in conf.c */
   argv[argc++] = "RRA:AVERAGE:0.5:1:240";
   argv[argc++] = "RRA:AVERAGE:0.5:24:240";
   argv[argc++] = "RRA:AVERAGE:0.5:168:240";
   argv[argc++] = "RRA:AVERAGE:0.5:672:240";
   argv[argc++] = "RRA:AVERAGE:0.5:5760:370";
#endif

   pthread_mutex_lock( &rrd_mutex );
   optind=0; opterr=0;
   rrd_clear_error();
   rrd_create(argc, argv);
   if(rrd_test_error())
      {
         err_msg("RRD_create: %s", rrd_get_error());
         pthread_mutex_unlock( &rrd_mutex );
         return 1;
      }
   debug_msg("Created rrd %s", rrd);
   pthread_mutex_unlock( &rrd_mutex );
   return 0;
}
QString
QMakeProperty::value(QString v, bool just_check)
{
    if(v == "QT_INSTALL_PREFIX")
        return QLibraryInfo::location(QLibraryInfo::PrefixPath);
    else if(v == "QT_INSTALL_DATA")
        return QLibraryInfo::location(QLibraryInfo::DataPath);
    else if(v == "QT_INSTALL_DOCS")
        return QLibraryInfo::location(QLibraryInfo::DocumentationPath);
    else if(v == "QT_INSTALL_HEADERS")
        return QLibraryInfo::location(QLibraryInfo::HeadersPath);
    else if(v == "QT_INSTALL_LIBS")
        return QLibraryInfo::location(QLibraryInfo::LibrariesPath);
    else if(v == "QT_INSTALL_BINS")
        return QLibraryInfo::location(QLibraryInfo::BinariesPath);
    else if(v == "QT_INSTALL_PLUGINS")
        return QLibraryInfo::location(QLibraryInfo::PluginsPath);
    else if(v == "QT_INSTALL_IMPORTS")
        return QLibraryInfo::location(QLibraryInfo::ImportsPath);
    else if(v == "QT_INSTALL_TRANSLATIONS")
        return QLibraryInfo::location(QLibraryInfo::TranslationsPath);
    else if(v == "QT_INSTALL_CONFIGURATION")
        return QLibraryInfo::location(QLibraryInfo::SettingsPath);
    else if(v == "QT_INSTALL_EXAMPLES")
        return QLibraryInfo::location(QLibraryInfo::ExamplesPath);
    else if(v == "QT_INSTALL_DEMOS")
        return QLibraryInfo::location(QLibraryInfo::DemosPath);
    else if(v == "QMAKE_MKSPECS")
        return qmake_mkspec_paths().join(Option::dirlist_sep);
    else if(v == "QMAKE_VERSION")
        return qmake_version();
#ifdef QT_VERSION_STR
    else if(v == "QT_VERSION")
        return QT_VERSION_STR;
#endif

    initSettings();
    int slash = v.lastIndexOf('/');
    QVariant var = settings->value(keyBase(slash == -1) + v);
    bool ok = var.isValid();
    QString ret = var.toString();
    if(!ok) {
        QString version = qmake_version();
        if(slash != -1) {
            version = v.left(slash-1);
            v = v.mid(slash+1);
        }
        settings->beginGroup(keyBase(false));
        QStringList subs = settings->childGroups();
        settings->endGroup();
        subs.sort();
        for (int x = subs.count() - 1; x >= 0; x--) {
            QString s = subs[x];
            if(s.isEmpty() || s > version)
                continue;
            var = settings->value(keyBase(false) + s + "/" + v);
            ok = var.isValid();
            ret = var.toString();
            if (ok) {
                if(!just_check)
                    debug_msg(1, "Fell back from %s -> %s for '%s'.", version.toLatin1().constData(),
                              s.toLatin1().constData(), v.toLatin1().constData());
                return ret;
            }
        }
    }
    return ok ? ret : QString();
}
Пример #3
0
void UserMainProc(void)
{
    NVTEVT evt;
    UINT32 paramNum;
    UINT32 paramArray[MAX_MESSAGE_PARAM_NUM];
    CHAR buffer[8]={0};	
    debug_msg("event loop - begin!\r\n");

//jacky lan for ACC power on detetion*********************
    //memcpy((void *)buffer, (void *)BLINFO_ACCPOWERON_FLAG, 8);
    if (rtc_getPWROnSource()==RTC_PWRON_SRC_PWR_SW4)
    {
        gbACCPowerOn=TRUE;
    }
    else if(rtc_getPWROnSource()==RTC_PWRON_SRC_PWR_SW)
    {
        gbACCPowerOn=FALSE;
    }
    else
    {
        gbACCPowerOn=FALSE;
    }		
    debug_msg("ACC FLAG :%d..\r\n",rtc_getPWROnSource());
//*************************************************	
#if (POWERON_TESTFLOW == ENABLE)
    //System_OnPowerPreInit();
    System_InstallMode();
    System_OnTimerInit();
    System_OnOutputInit();
    GxSystem_BootStart();

    if(GxSystem_GetPowerOnSource() == GX_PWRON_SRC_PWR_VBUS)
    {
        GxUSB_Init(TRUE);
    }
    if(gIsUSBChargePreCheck)
    {
        UINT32 uiChargeCurrent = USB_CHARGE_CURRENT_2P5MA;
        System_OnUsbInit();
        System_OnStrgInit_INMEM();
        System_OnStrgInit_EXMEM();
        Install_AppObj(); //must install before any event dispatch
        UI_UnlockEvent();
        debug_msg("wait USB - begin\r\n");
        do
        {
            UserWaitEvent(NVTEVT_USB_CHARGE_CURRENT, &paramNum, paramArray); //(paramNum == 1 && paramArray[0] == 0) //power-on begin
            uiChargeCurrent = paramArray[0];
            debug_msg("USB charging current(%d)\r\n",paramArray[0]);
        }
        while(uiChargeCurrent < USB_CHARGE_CURRENT_500MA);
        debug_msg("wait USB - end\r\n");
        //SxCmd_DoCommand("dma eclk");
        ///GxLED_SetCtrl(KEYSCAN_LED_FCS,TURNON_LED,TRUE);
    }
    //UserWaitEvent(NVTEVT_SYSTEM_BOOT, &paramNum, paramArray); //(paramNum == 1 && paramArray[0] == 0) //power-on begin

    //////////////////////////////////////////////////////////////
    // Direct boot flow

    //Init Device & Lib
    SysDbgUtCmd_Init(); //Init Once DbgUt
    System_OnVideoInit();
    System_OnAudioInit();
    if(!gIsUSBChargePreCheck)
    {
    System_OnStrgInit_INMEM();
    System_OnStrgInit_EXMEM();
    System_OnStrgInit_FWS();
    System_OnStrgInit_PS();
    System_OnStrgInit_FS();
    System_OnUsbInit();
    }
    System_OnLensInit();
    System_OnSensorInit();
    System_OnPowerInit();
    System_OnInputInit();

    //////////////////////////////////////////////////////////////

    //Init object list for UIControl event process
    if(!gIsUSBChargePreCheck)
        Install_AppObj(); //must install before any event dispatch

    //UserWaitEvent(NVTEVT_SYSTEM_BOOT, &paramNum, paramArray); //(paramNum == 1 && paramArray[0] == 0) //power-on begin
    Ux_SendEvent(0, NVTEVT_SYSTEM_BOOT, 1, 1);

#else

    System_OnStrgInit_INMEM();
    System_OnStrgInit_FWS();
    System_OnStrg_DownloadFW(UserSection_Order_full, UserSection_LoadCb);
    System_OnPowerPreInit();
    System_InstallMode();
    System_OnTimerInit();
    System_OnOutputInit();
    GxSystem_BootStart();
    //UserWaitEvent(NVTEVT_SYSTEM_BOOT, &paramNum, paramArray); //(paramNum == 1 && paramArray[0] == 0) //power-on begin

    //////////////////////////////////////////////////////////////
    // Direct boot flow

    //Init Device & Lib
    //#NT#2013/2/20#Philex Lin - begin
    // for pressing longer to power up system

	#if (UI_STYLE==UI_STYLE_DRIVER)
      #if (LONG_STARTUP == ENABLE)
	  usb_open();   
	  debug_msg("usb_StateChange :%d--->power source :%d--->update\r\n",usb_StateChange(),GxSystem_GetPowerOnSource());
	 // if(((GxSystem_GetPowerOnSource() == USB_SOURCE_POWERON)&&(usb_StateChange()==TRUE))||(GxSystem_GetPowerOnSource() == GSENSOR_TRIGGER_SOURCE_POWERON))
	if(((GxSystem_GetPowerOnSource() == USB_SOURCE_POWERON)&&(usb_StateChange()==TRUE))||(gBinInfo.ld.LdCtrl2 & LDCF_UPDATE_FW)||(GxSystem_GetPowerOnSource() == GSENSOR_TRIGGER_SOURCE_POWERON))

	 {	   
		usb_close();		 
	       System_OnVideoInit();
	}
	else
	{
	usb_close();		
       SysInit_ResetShutDownTimer();
       while (guiResetSDTimerCount < RESET_SHUTDOWN_TIMER_COUNT)
        ;
       System_OnVideoInit();
	}
      #else
       System_OnVideoInit();
      #endif
    #else
    System_OnVideoInit();
    #endif
    //#NT#2013/2/20#Philex Lin - end
    
	  
    System_OnAudioInit();    
    System_OnStrgInit_EXMEM();
    System_OnStrgInit_PS();
    System_OnStrgInit_FS();
    System_OnUsbInit();
    #if (UI_STYLE==UI_STYLE_DRIVER)
    usb_setConfig(USB_CONFIG_ID_STANDARD_CHARGER, FALSE);
    #endif

    #if 1//(LENS_FUNCTION == ENABLE)
    System_OnLensInit();
    #endif
    System_OnSensorInit();
    System_OnPowerInit();
    System_OnInputInit();
   
    //////////////////////////////////////////////////////////////

    //Init object list for UIControl event process
    Install_AppObj(); //must install before any event dispatch

    #if (UI_STYLE==UI_STYLE_DRIVER)
        aud_setTotalVolLevel(AUDIO_VOL_LEVEL8);
        #if (UPDATE_CFG == UPDATE_CFG_YES)
        // Do UI_LoadCfgFile() function
        UI_LoadCfgFile();
        #endif
    #endif
    DscMovie_SetFDB_ROFolder("RO");	//设置加锁文件名
    //UserWaitEvent(NVTEVT_SYSTEM_BOOT, &paramNum, paramArray); //(paramNum == 1 && paramArray[0] == 0) //power-on begin
    Ux_SendEvent(0, NVTEVT_SYSTEM_BOOT, 1, 1);
#endif

    while(!bUI_Quit)
    {
        Ux_WaitEvent(&evt, &paramNum, paramArray);
        if(evt)
        {
            INT32 result = NVTEVT_PASS;
            DBG_IND("^YMSG: get event %08x!\r\n", evt);

            if(IS_KEY_EVENT(evt))
                result = System_UserKeyFilter(evt, paramNum, paramArray);
            #if (TOUCH_FUNCTION == ENABLE)
            if(result != NVTEVT_CONSUME)
            {
                if(IS_TOUCH_EVENT(evt))
                    result = System_UserTouchFilter(evt, paramNum, paramArray);
            }
            #endif
            if(result != NVTEVT_CONSUME)
            {
                if(IS_APP_EVENT(evt))
                    result = Ux_AppDispatchMessage(evt, paramNum, paramArray);
            }
            if(result != NVTEVT_CONSUME)
                result = Ux_WndDispatchMessage(evt, paramNum, paramArray);

            Ux_Redraw();
#if 0 //background task wait done flag,need to remove
            // A special case.
            // UI background is busy until finishing the event handler of BACKGROUND_DONE
            if (evt == NVTEVT_BACKGROUND_DONE)
            {
                BKG_Done();
            }
#endif
            //return result;
        }
    }

    //////////////////////////////////////////////////////////////
    //System_PowerOff(SYS_POWEROFF_NORMAL);

    //Exit Lib & Device
    System_OnVideoExit();
    System_OnAudioExit();
    System_OnStrgExit_FS();
    System_OnStrgExit_PS();
    System_OnStrgExit_FWS();
    System_OnStrgExit_EXMEM();
    System_OnStrgExit_INMEM();
    System_OnUsbExit();
    System_OnLensExit();
    System_OnSensorExit();
    System_OnPowerExit();
    System_OnInputExit();
    System_OnOutputExit();
    System_OnTimerExit();

    //////////////////////////////////////////////////////////////
    GxSystem_ShutDownEnd();
    GxSystem_PowerOff();
    debug_msg("event loop - end!\r\n");
}
Пример #4
0
bool QMakeSourceFileInfo::findMocs(SourceFile *file)
{
    if(file->moc_checked)
        return true;
    files_changed = true;
    file->moc_checked = true;

    int buffer_len;
    char *buffer = 0;
    {
        struct stat fst;
        int fd;
#if defined(_MSC_VER) && _MSC_VER >= 1400
        if (_sopen_s(&fd, fixPathForFile(file->file, true).local().toLocal8Bit().constData(),
            _O_RDONLY, _SH_DENYRW, _S_IREAD) != 0)
            fd = -1;
#else
        fd = open(fixPathForFile(file->file, true).local().toLocal8Bit().constData(), O_RDONLY);
#endif
        if(fd == -1 || fstat(fd, &fst) || S_ISDIR(fst.st_mode))
            return false; //shouldn't happen
        buffer = getBuffer(fst.st_size);
        for(int have_read = buffer_len = 0;
            (have_read = QT_READ(fd, buffer + buffer_len, fst.st_size - buffer_len));
            buffer_len += have_read);
        QT_CLOSE(fd);
    }

    debug_msg(2, "findMocs: %s", file->file.local().toLatin1().constData());
    int line_count = 1;
    bool ignore_qobject = false, ignore_qgadget = false;
 /* qmake ignore Q_GADGET */
 /* qmake ignore Q_OBJECT */
    for(int x = 0; x < buffer_len; x++) {
        if(*(buffer + x) == '/') {
            ++x;
            if(buffer_len >= x) {
                if(*(buffer + x) == '/') { //c++ style comment
                    for(;x < buffer_len && !qmake_endOfLine(*(buffer + x)); ++x);
                } else if(*(buffer + x) == '*') { //c style comment
                    for(++x; x < buffer_len; ++x) {
                        if(*(buffer + x) == 't' || *(buffer + x) == 'q') { //ignore
                            if(buffer_len >= (x + 20) &&
                               !strncmp(buffer + x + 1, "make ignore Q_OBJECT", 20)) {
                                debug_msg(2, "Mocgen: %s:%d Found \"qmake ignore Q_OBJECT\"",
                                          file->file.real().toLatin1().constData(), line_count);
                                x += 20;
                                ignore_qobject = true;
                            } else if(buffer_len >= (x + 20) &&
                                      !strncmp(buffer + x + 1, "make ignore Q_GADGET", 20)) {
                                debug_msg(2, "Mocgen: %s:%d Found \"qmake ignore Q_GADGET\"",
                                          file->file.real().toLatin1().constData(), line_count);
                                x += 20;
                                ignore_qgadget = true;
                            }
                        } else if(*(buffer + x) == '*') {
                            if(buffer_len >= (x+1) && *(buffer + (x+1)) == '/') {
                                ++x;
                                break;
                            }
                        } else if(Option::debug_level && qmake_endOfLine(*(buffer + x))) {
                            ++line_count;
                        }
                    }
                }
            }
        } else if(*(buffer+x) == '\'' || *(buffer+x) == '"') {
            const char term = *(buffer+(x++));
            while(x < buffer_len) {
                if(*(buffer+x) == term)
                    break;
                if(*(buffer+x) == '\\') {
                    x+=2;
                } else {
                    if(qmake_endOfLine(*(buffer+x)))
                        ++line_count;
                    ++x;
                }
            }
        }
        if(Option::debug_level && qmake_endOfLine(*(buffer+x)))
            ++line_count;
        if(((buffer_len > x+2 &&  *(buffer+x+1) == 'Q' && *(buffer+x+2) == '_')
                   ||
            (buffer_len > x+4 &&  *(buffer+x+1) == 'Q' && *(buffer+x+2) == 'O'
                              &&  *(buffer+x+3) == 'M' && *(buffer+x+4) == '_'))
                   &&
                  *(buffer + x) != '_' &&
                  (*(buffer + x) < 'a' || *(buffer + x) > 'z') &&
                  (*(buffer + x) < 'A' || *(buffer + x) > 'Z') &&
                  (*(buffer + x) < '0' || *(buffer + x) > '9')) {
            ++x;
            int match = 0;
            static const char *interesting[] = { "OBJECT", "GADGET",
                                                 "M_OBJECT" };
            for(int interest = 0, m1, m2; interest < 3; ++interest) {
                if(interest == 0 && ignore_qobject)
                    continue;
                else if(interest == 1 && ignore_qgadget)
                    continue;
                for(m1 = 0, m2 = 0; *(interesting[interest]+m1); ++m1) {
                    if(*(interesting[interest]+m1) != *(buffer+x+2+m1)) {
                        m2 = -1;
                        break;
                    }
                    ++m2;
                }
                if(m1 == m2) {
                    match = m2 + 2;
                    break;
                }
            }
            if(match && *(buffer+x+match) != '_' &&
               (*(buffer+x+match) < 'a' || *(buffer+x+match) > 'z') &&
               (*(buffer+x+match) < 'A' || *(buffer+x+match) > 'Z') &&
               (*(buffer+x+match) < '0' || *(buffer+x+match) > '9')) {
                if(Option::debug_level) {
                    *(buffer+x+match) = '\0';
                    debug_msg(2, "Mocgen: %s:%d Found MOC symbol %s", file->file.real().toLatin1().constData(),
                              line_count, buffer+x);
                }
                file->mocable = true;
                return true;
            }
        }
    }
    return true;
}
Пример #5
0
/** Return pointer to virtual bus list.
  */
struct usb_bus* usb_get_busses(void)
{
   //! \todo Merge both local - attached busses in future?
   debug_msg("returned %p", __remote_bus);
   return __remote_bus;
}
Пример #6
0
// the third comparision
// 0 - same file
// 1 - different file
int compare_file_blocks(list_node *file1, list_node *file2)
{
    unsigned int file_size = (unsigned int)file1->filesize;
    if (debug_mod)
    {
        char *subpath[2];
        subpath[0] = pathtrim(file1->filepath);
        subpath[1] = pathtrim(file2->filepath);
        debug_msg("Block Checking: File name: %s\t%s", subpath[0], subpath[1]);
    }
    FILE *f1, *f2;
    char tmp1, tmp2;
    int i;
    f1 = fopen(file1->filepath, "rb");
    f2 = fopen(file2->filepath, "rb");
    if (f1 == NULL || f2 == NULL)
    {
        perror("File open failed");
    }
    debug_msg("Open files successfully");
    if (file_size > MIN_BLOCK_COMPARE_SIZE)
    {
        // scan the beginning
        debug_msg("Begin block checking...");
        fseek(f1, 0, SEEK_SET);
        fseek(f2, 0, SEEK_SET);
        for (i = 0; i < BLOCK_SIZE; i++)
        {
            fread(&tmp1, 1, 1, f1);
            fread(&tmp2, 1, 1, f2);
            //debug_msg("fread");
            if (tmp1 != tmp2)
            {
                //debug_msg("block diff 1");
                fclose(f1);
                fclose(f2);
                return 1;
            }
        }
        // scan the end
        debug_msg("End block checking...");
        fseek(f1, file_size - BLOCK_SIZE, SEEK_SET);
        fseek(f2, file_size - BLOCK_SIZE, SEEK_SET);
        for (i = 0; i < BLOCK_SIZE; i++)
        {
            fread(&tmp1, 1, 1, f1);
            fread(&tmp2, 1, 1, f2);
            if (tmp1 != tmp2)
            {
                debug_msg("block diff 2");
                fclose(f1);
                fclose(f2);
                return 1;
            }
        }
        // randomly scan the middle
        debug_msg("Random Checking...");
        long offset = (rand() % (file_size - 2 * BLOCK_SIZE)) + 100;
        fseek(f1, offset, SEEK_SET);
        fseek(f2, offset, SEEK_SET);
        for (i = 0; i < BLOCK_SIZE; i++)
        {
            fread(&tmp1, 1, 1, f1);
            fread(&tmp2, 1, 1, f2);
            if (tmp1 != tmp2)
            {
                debug_msg("block diff 3");
                fclose(f1);
                fclose(f2);
                return 1;
            }
        }
    }
    else
    {
        debug_msg("File too small, check the whole");
        for (i = 0; i < file_size; i++)
        {
            fread(&tmp1, 1, 1, f1);
            fread(&tmp2, 1, 1, f2);
            if (tmp1 != tmp2)
            {

                fclose(f1);
                fclose(f2);
                return 1;
            }
        }
    }
    fclose(f1);
    fclose(f2);
    debug_msg("Block Checking finished");
    return 0;
}
Пример #7
0
void GPSRecTsk(void)
{
    CHAR      cLen;
    USHORT    CheckSentenceType1, CheckSentenceType2;
    UINT32    CheckSentenceType3;
    CHAR      RecSentence[NMEA_SENTENCE_SIZE];
    CHAR      *pSentenceData;
    CHAR      *ptrGPSData;

    debug_msg("Enter GPS Receive task\r\n");
    ptrTmpGPSData = pGPSLogAddr;
    clr_flg(FLG_ID_GPS, GPS_FLAG_DATAVALID);

    while(1)
    {

        cLen = NMEA_SENTENCE_SIZE ;
        #if (RECEIVE_FROM_UART2)
        if (uart2_getString(RecSentence, &cLen) == E_PAR)
        #else
        if (uart_getString(RecSentence, &cLen) == E_PAR)
        #endif
            debug_err(("UART2: parameter error!\r\n"));


        //Each NMEA sentence begins with '$' (0x24)
        if (RecSentence[0] == 0x24)
        {
            pSentenceData = RecSentence;
            CheckSentenceType1 = *(USHORT *)(pSentenceData + 2);
            CheckSentenceType2 = *(USHORT *)(pSentenceData + 4);
            CheckSentenceType3 = ((UINT)CheckSentenceType2 << 16) | (UINT)CheckSentenceType1;

            switch(CheckSentenceType3)
            {
            case GSA_SENTENCE:
                //NMEASentence.GSA = RecSentence;
                //GPSRec_NMEAParser(RecSentence, (UINT32)cLen, GSA);
                break;

            case RMC_SENTENCE:
                // verify address to avoid buffer overflow !!
                if (bzLogGPS == TRUE)
                {
                    // get g-sensor axis data
                    //gsensor_GetData(&GS_Data);
                    ptrTmpGPSData = (CHAR *)GPSRec_VerifyBufAddr((UINT32)ptrTmpGPSData);
                    //ptrTmpGPSData += sprintf(ptrTmpGPSData,"$G&%s;$S&\r\n",&RecSentence[1]);
                    ptrTmpGPSData += sprintf(ptrTmpGPSData,"$%s\r\n",&RecSentence[1]);					
			 //ptrTmpGPSData = pGPSLogAddr;
			 //sprintf(ptrTmpGPSData,"$G&%s;$S&\r\n",&RecSentence[1]);
                }
                NMEASentence.RMC = RecSentence;
                NMEA_debug(("%s\r\n",RecSentence));
				
                GPSRec_NMEAParser(RecSentence, (UINT32)cLen, RMC);
                break;

            case GGA_SENTENCE:
                //NMEASentence.GGA = RecSentence;
                //GPSRec_NMEAParser(RecSentence, (UINT32)cLen, GGA);
                break;

            case GSV_SENTENCE:
                //NMEASentence.GSV = RecSentence;
                //GPSRec_NMEAParser(RecSentence, (UINT32)cLen, GSV);
                break;

            case GLL_SENTENCE:
                //NMEASentence.GLL = RecSentence;
                //GPSRec_NMEAParser(RecSentence, (UINT32)cLen, GLL);
                break;

            case VTG_SENTENCE:
                //NMEASentence.VTG = RecSentence;
                //GPSRec_NMEAParser(RecSentence, (UINT32)cLen, VTG);
                break;
            case ZDA_SENTENCE:
               GPS_debug(("#ZDA.... \r\n"));				
		   break;
            default:
                debug_err(("GPS: Can't identify this sentence 0x%X \r\n",CheckSentenceType3));
                break;
            }


        }




    }

}
Пример #8
0
int main(void)
{
   int s, t, len, skip_cmd = 0;
   struct sockaddr_un remote;
   char msgbuf[4096], buf[UNIX_PATH_MAX], *env;

   if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1)
     {
        perror("socket");
        exit(1);
     }

   printf("Trying to connect...\n");

   remote.sun_family = AF_UNIX;
   env = getenv("EVAS_CSERVE2_SOCKET");
   if (!env)
     {
        snprintf(buf, sizeof(buf), "/tmp/.evas-cserve2-%x.socket",
                 (int)getuid());
        env = buf;
     }
   eina_strlcpy(remote.sun_path, env, UNIX_PATH_MAX);
   len = strlen(remote.sun_path) + sizeof(remote.sun_family);
   if (connect(s, (struct sockaddr *)&remote, len) == -1)
     {
        perror("connect");
        exit(1);
     }

   printf("Connected.\n");

   while(!feof(stdin))
     {
        char cmd[1024];
        int i;
        int size;
        void *msg;

        if (skip_cmd)
          skip_cmd = 0;
        else
          printf("\n> ");
        if (!fgets(cmd, sizeof(cmd), stdin))
          break;
        len = strlen(cmd) - 1;
        cmd[len] = '\0';

        if (!len)
          {
             skip_cmd = 1;
             continue;
          }

        for (i = 0; _msg_types[i].name; i++)
          {
             if (!strcmp(cmd, _msg_types[i].name))
               break;
          }

        // discards the end of the message if we can't parse it
        if (!_msg_types[i].name)
          {
             printf("Invalid command.\n");
             continue;
          }

        if (!_msg_types[i].parse_func)
          {
             printf("Command %s still unhandled.\n", _msg_types[i].name);
             continue;
          }

        msg = _msg_types[i].parse_func(&size);

        if (send(s, &size, sizeof(size), MSG_NOSIGNAL) == -1)
          {
             perror("send size");
             exit(1);
          }
        if (send(s, msg, size, MSG_NOSIGNAL) == -1)
          {
             perror("send");
             exit(1);
          }

        free(msg);

        usleep(100000);

        if ((t=recv(s, &size, sizeof(size), MSG_DONTWAIT)) > 0)
          {
             len = recv(s, msgbuf, size, 0);
             printf("size of received message: %d\n", len);
             if (len != size)
               {
                  printf("couldn't read entire message.\n");
                  continue;
               }
             debug_msg(&size, sizeof(size));
             debug_msg(msgbuf, size);
             parse_answer(msgbuf);
          }
        else
          {
             if (t < 0 && ((errno == EAGAIN) || (errno == EWOULDBLOCK)))
               continue;
             else fprintf(stderr, "Server closed connection\n");
             exit(1);
          }
     }

   close(s);

   return 0;
}
Пример #9
0
Ganglia_udp_send_channels
Ganglia_udp_send_channels_create( Ganglia_pool p, Ganglia_gmond_config config )
{
  apr_array_header_t *send_channels = NULL;
  cfg_t *cfg=(cfg_t *)config;
  int i, num_udp_send_channels = cfg_size( cfg, "udp_send_channel");
  apr_pool_t *context = (apr_pool_t*)p;

  /* Return null if there are no send channels specified */
  if(num_udp_send_channels <= 0)
    return (Ganglia_udp_send_channels)send_channels;

  /* Create my UDP send array */
  send_channels = apr_array_make( context, num_udp_send_channels, 
                                  sizeof(apr_socket_t *));

  for(i = 0; i< num_udp_send_channels; i++)
    {
      cfg_t *udp_send_channel;
      char *mcast_join, *mcast_if, *host;
      int port, ttl, bind_hostname;
      apr_socket_t *socket = NULL;
      apr_pool_t *pool = NULL;
      char *bind_address;

      udp_send_channel = cfg_getnsec( cfg, "udp_send_channel", i);
      host           = cfg_getstr( udp_send_channel, "host" );
      mcast_join     = cfg_getstr( udp_send_channel, "mcast_join" );
      mcast_if       = cfg_getstr( udp_send_channel, "mcast_if" );
      port           = cfg_getint( udp_send_channel, "port");
      ttl            = cfg_getint( udp_send_channel, "ttl");
      bind_address   = cfg_getstr( udp_send_channel, "bind" );
      bind_hostname  = cfg_getbool( udp_send_channel, "bind_hostname");

      debug_msg("udp_send_channel mcast_join=%s mcast_if=%s host=%s port=%d\n",
                mcast_join? mcast_join:"NULL", 
                mcast_if? mcast_if:"NULL",
                host? host:"NULL",
                port);

      if(bind_address != NULL && bind_hostname == cfg_true)
        {
          err_msg("udp_send_channel: bind and bind_hostname are mutually exclusive, both parameters can't be specified for the same udp_send_channel\n");
          exit(1);
        }

      /* Create a subpool */
      apr_pool_create(&pool, context);

      /* Join the specified multicast channel */
      if( mcast_join )
        {
          /* We'll be listening on a multicast channel */
          socket = create_mcast_client(pool, mcast_join, port, ttl, mcast_if, bind_address, bind_hostname);
          if(!socket)
            {
              err_msg("Unable to join multicast channel %s:%d. Exiting\n",
                  mcast_join, port);
              exit(1);
            }
        }
      else
        {
          /* Create a UDP socket */
          socket = create_udp_client( pool, host, port, mcast_if, bind_address, bind_hostname );
          if(!socket)
            {
              err_msg("Unable to create UDP client for %s:%d. Exiting.\n",
                      host? host: "NULL", port);
              exit(1);
            }
        }

      /* Add the socket to the array */
      *(apr_socket_t **)apr_array_push(send_channels) = socket;
    }

  return (Ganglia_udp_send_channels)send_channels;
}
Пример #10
0
INT32 UIFlowWndWiFiMovie_OnExeKeyShutter2(BOOL StartOrStop)
{
    BOOL startRec =0;
    UINT32 uiNotifyAPPStatus = 0;
    UINT32 result = WIFIAPP_RET_OK;
    UINT32 curStatus = 0;

    startRec = StartOrStop;
    if (System_GetState(SYS_STATE_CURRMODE) != PRIMARY_MODE_MOVIE)
    {
        WifiCmd_Done(WIFIFLAG_RECORD_DONE,WIFIAPP_RET_STATE_ERR);
        UIFlowWndWiFiMovieErrMsg("not movie mode\r\n");
        return NVTEVT_CONSUME;
    }
    debug_msg("UIFlowWndWiFiMovie_OnExeKeyShutter2---\r\n");
    curStatus = UIFlowWndWiFiMovie_GetStatus();
    if(startRec)
    {
        if (curStatus == WIFI_MOV_ST_LVIEW)
        {
            UINT32 MaxTime = UIFlowWiFiMovie_GetMaxRecTime();

            if((MaxTime <= 2) && (SysGetFlag(FL_MOVIE_CYCLIC_REC) == MOVIE_CYCLICREC_OFF))
            {
                result = WIFIAPP_RET_STORAGE_FULL;
                UIFlowWndWiFiMovieErrMsg("recTime<2 sec\r\n");
            }
            else
            {
                // Reset Current record time
                FlowMovie_SetRecCurrTime(0);

                // Send socket to notify APP movie recording is started.
                // if(uiNotifyAPPStatus)
                // {
                //     WifiApp_SendCmd(WIFIAPP_CMD_NOTIFY_STATUS, WIFIAPP_RET_RECORD_STARTED);
                //  }
                //   else
                //   {
                WifiApp_SendCmd(WIFIAPP_CMD_NOTIFY_STATUS, WIFIAPP_RET_RECORD_STARTED);
                FlowWiFiMovie_StopRec();
                FlowWiFiMovie_StartRec(WIFI_RTSP_REC);
                //  }
            }
        }
        else if(curStatus == WIFI_MOV_ST_IDLE)
        {
            result = WIFIAPP_RET_FAIL;
            UIFlowWndWiFiMovieErrMsg("idle state,cannot record\r\n");
        }
    }
    else  //stop rec
    {
        UINT32 recordTime = FlowMovie_GetRecCurrTime();
        if ((curStatus == WIFI_MOV_ST_RECORD) && ((recordTime >= 1) || (SysGetFlag(FL_MOVIE_TIMELAPSE_REC) != MOVIE_TIMELAPSEREC_OFF)))
        {
            if(UxCtrl_IsShow(&UIMenuWndWiFiModeLink_PanelCtrl))
            {
                UxCtrl_SetShow(&UIMenuWndWiFiModeLink_PanelCtrl,FALSE);
            }
            if(UxCtrl_IsShow(&UIMenuWndWiFiMobileLinkOK_PanelCtrl))
            {
                UxCtrl_SetShow(&UIMenuWndWiFiMobileLinkOK_PanelCtrl,FALSE);
            }

            if(g_bgsensor==TRUE)
            {
                g_bgsensor = FALSE;
            }
            WifiApp_SendCmd(WIFIAPP_CMD_NOTIFY_STATUS, WIFIAPP_RET_RECORD_STOPPED);

            FlowWiFiMovie_StopRec();
            FlowWiFiMovie_StartRec(WIFI_RTSP_LIVEVIEW);
            // Notify Maximum Record Time
            UI_SetData(FL_WIFI_MOVIE_MAXRECTIME, UIMovRecObj_GetData(RECMOVIE_MAXSECOND));
        }
        else if ((curStatus == WIFI_MOV_ST_RECORD) &&(recordTime < 1))
        {
            result = WIFIAPP_RET_FAIL;
            UIFlowWndWiFiMovieErrMsg("recTime<1 sec %d sts %d\r\n",recordTime,UIFlowWndWiFiMovie_GetStatus());
        }
        else if(curStatus == WIFI_MOV_ST_IDLE)
        {
            result = WIFIAPP_RET_FAIL;
            UIFlowWndWiFiMovieErrMsg("idle state,cannot stop\r\n");
        }
    }
    // Notify Done
    WifiCmd_Done(WIFIFLAG_RECORD_DONE,result);
    return NVTEVT_CONSUME;
}
Пример #11
0
bool
BuildsMetaMakefileGenerator::write(const QString &oldpwd)
{
    Build *glue = 0;
    if(!makefiles.isEmpty() && !makefiles.first()->build.isNull()) {
        glue = new Build;
        glue->name = name;
        glue->makefile = createMakefileGenerator(project, true);
        makefiles += glue;
    }

    bool ret = true;
    const QString &output_name = Option::output.fileName();
    for(int i = 0; ret && i < makefiles.count(); i++) {
        Option::output.setFileName(output_name);
        Build *build = makefiles[i];

        bool using_stdout = false;
        if(build->makefile && (Option::qmake_mode == Option::QMAKE_GENERATE_MAKEFILE ||
                               Option::qmake_mode == Option::QMAKE_GENERATE_PROJECT)
           && (!build->makefile->supportsMergedBuilds()
            || (build->makefile->supportsMergedBuilds() && (!glue || build == glue)))) {
            //open output
            if(!(Option::output.isOpen())) {
                if(Option::output.fileName() == "-") {
                    Option::output.setFileName("");
                    Option::output_dir = qmake_getpwd();
                    Option::output.open(stdout, QIODevice::WriteOnly | QIODevice::Text);
                    using_stdout = true;
                } else {
                    if(Option::output.fileName().isEmpty() &&
		       Option::qmake_mode == Option::QMAKE_GENERATE_MAKEFILE)
                        Option::output.setFileName(project->first("QMAKE_MAKEFILE"));
                    Option::output_dir = oldpwd;
                    QString build_name = build->name;
                    if(!build->build.isEmpty()) {
                        if(!build_name.isEmpty())
                            build_name += ".";
                        build_name += build->build;
                    }
                    if(!build->makefile->openOutput(Option::output, build_name)) {
                        fprintf(stderr, "Failure to open file: %s\n",
                                Option::output.fileName().isEmpty() ? "(stdout)" :
                                Option::output.fileName().toLatin1().constData());
                        return false;
                    }
                }
            }
        } else {
           using_stdout = true; //kind of..
        }

        if(!build->makefile) {
            ret = false;
        } else if(build == glue) {
            ret = build->makefile->writeProjectMakefile();
        } else {
            ret = build->makefile->write();
            if (glue && glue->makefile->supportsMergedBuilds())
                ret = glue->makefile->mergeBuildProject(build->makefile);
        }
        if(!using_stdout) {
            Option::output.close();
            if(!ret)
                Option::output.remove();
        }

        // debugging
        if(Option::debug_level) {
            QMap<QString, QStringList> &vars = project->variables();
            for(QMap<QString, QStringList>::Iterator it = vars.begin(); it != vars.end(); ++it) {
                if(!it.key().startsWith(".") && !it.value().isEmpty())
                    debug_msg(1, "%s === %s", it.key().toLatin1().constData(),
                              it.value().join(" :: ").toLatin1().constData());
            }
        }
    }
    return ret;
}
Пример #12
0
INT32 UIFlowWndWiFiMovie_OnTimer(VControl *pCtrl, UINT32 paramNum, UINT32 *paramArray)
{
    UINT32  uiEvent;
    uiEvent = paramNum ? paramArray[0] : 0;
    switch(uiEvent)
    {
    case NVTEVT_05SEC_TIMER:
        break;
        // Motion Detect function
        if (SysGetFlag(FL_MOVIE_MOTION_DET) == MOVIE_MOTIONDET_ON)
        {
            static UINT32  uiMotionDetGo = 0;
            static UINT32  uiMotionDetStop = 0;

            if (MD_Process()==TRUE)
            {
                uiMotionDetGo++;
                if (uiMotionDetGo>=2)
                {
                    uiMotionDetStop=0;
                    if (UIFlowWndWiFiMovie_GetStatus() == WIFI_MOV_ST_LVIEW)
                    {
                        debug_msg("^GStart Record\r\n");
                        // reset uiMotionDetGo
                        uiMotionDetGo = 0;
                        // Post event to record video and send socket to notify APP recording is started.
                        Ux_PostEvent(NVTEVT_WIFI_EXE_MOVIE_REC, 2, 1, 1);
                    }
                }
            }
            else
            {
                uiMotionDetStop++;
                if (uiMotionDetStop>=2) // 1 sec
                {
                    uiMotionDetGo=0;
                }
#if 1
                if (uiMotionDetStop>=20) // 10 Sec
#else
                if (uiMotionDetStop>=65536) // 10 Sec
#endif
                {
                    uiMotionDetStop = 0;
                    if (UIFlowWndWiFiMovie_GetStatus() == WIFI_MOV_ST_RECORD)
                    {
                        if (FlowMovie_GetRecCurrTime() >= 1 || (SysGetFlag(FL_MOVIE_TIMELAPSE_REC) != MOVIE_TIMELAPSEREC_OFF))
                        {
#if 0
                            FlowWiFiMovie_StopRec();
                            FlowWiFiMovie_StartRec(WIFI_RTSP_LIVEVIEW);
                            if ( FALSE == AE_Wait_Stable(3, 60) )
                                debug_msg("Motion Detection: AE do not stable\r\n");
#endif
                            debug_msg("^RWIFIAPP_RET_RECORD_STOPPED\r\n");
                            WifiApp_SendCmd(WIFIAPP_CMD_NOTIFY_STATUS, WIFIAPP_RET_RECORD_STOPPED);
                        }
                        break;
                    }
                }
            }
        }

        break;
    }

    Ux_DefaultEvent(pCtrl,NVTEVT_TIMER,paramNum,paramArray);
    return NVTEVT_CONSUME;
}
Пример #13
0
int
do_dos_command (void)
{
	//XXX missing the rename command
  /* execute the DOS command in the buffer */
  int i = curr_client, dt = -1, ds = -1;
  /* scratch vars */
  int j, k, par, rv;
  unsigned int a,start;
  uchar path[1024], partition[8];
  uchar temp[1024];
  uchar name[80], id[80];
  debug_msg ("DOS Command: [%s]\n", dos_command[i]);
  if (dos_comm_len[i] == 0)
    /* null command needs null action */
    return (0);

    /* strip "0:" off the DOS command, leave only ':' */

//  for (j=0;j<=dos_comm_len[i];j++) {
//    if ((dos_command[i][j]=='0')&&(dos_command[i][j+1]==':')) {
//	for (k=j+1;k<=dos_comm_len[i];k++)
//	    dos_command[i][k-1]=dos_command[i][k];
//	dos_comm_len[i] = dos_comm_len[i]-1;
//    }
//  }
// debug_msg ("DOS Command: [%s]\n", dos_command[i]);


  /* parse out */
  switch (dos_command[i][0])
  {
  case 'M':
    {
      /* MkDir */
      switch (dos_command[i][1])
      {
      case '-':
        /* M-R and M-W */
        switch (dos_command[i][2])
        {
	case 'R':
	    { int addr, k;
	      addr = dos_command[i][3]+256*dos_command[i][4];
	      debug_msg("M-R on $%04x for $%02x\n",addr,dos_command[i][5]);
	      for (k=0;k<dos_command[i][5];k++) {
	        dos_status[i][k]=drive_memory[i][addr+k];
		}
	      dos_stat_len[i]=dos_command[i][5];
	      dos_comm_len[i] = 0;
	      return 0;
	    }
	    break;
	case 'W':
	    { int addr, k;
	      addr = dos_command[i][3]+256*dos_command[i][4];
	      debug_msg("M-W on $%04x for $%02x\n",addr,dos_command[i][5]);
	      for (k=0;k<dos_command[i][5];k++)
	        drive_memory[i][addr+k]=dos_status[i][k+6];
	      dos_comm_len[i] = 0;
	      set_error (0, 0, 0);
	      return 0;
	    }
	    break;
	}
	break;
      case 'D':
	/* make conventional dir */
	dos_comm_len[i] = 0;
	set_error (38, 0, 0);
	return (-1);
	break;
      case 'd':
      case 196:
	{
	  /* make special dir */
	  int dt = dos_command[i][2];
	  int media = 0, par, blocks = 0xffffff, size = 0;
	  uchar path[1024], sname[256], lname[256], ext[8];
	  fs64_filesystem fs;
	  fs.fsfile = 0;
	  switch (dt)
	  {
	  case '4':
	  case '6':		/* 1541 (D64) */
	    media = media_D64;
	    blocks = 683 + 1;
	    break;
	  case '7':		/* 1571 (D71) */
	    media = media_D71;
	    blocks = 683 * 2 + 1;
	    break;
	  case '8':		/* 1581 (D81) */
	    media = media_D81;
	    blocks = 80 * 40 + 1;
	    break;
	  case 'N':
	  case 'H':		/* CMD "Native" (DHD) */
	    media = media_DHD;
	    if (!dos_command[i][3])
	      dos_command[i][3] = 0xff;
	    blocks = 256 * dos_command[i][3] + 2;
	    size = dos_command[i][3];
	    break;
	  case 'T':		/* T64 */
	  case 'L':		/* LNX */
	    set_error (38, 0, 0);
	    return (-1);
	  default:
	    /* 79,INVALID MEDIA,00,00 */
	    set_error (79, 0, 0);
	  }
	  /* find where `:' is (if at all) */
	  lname[0] = 0;
	  for (j = 4; j < dos_comm_len[i]; j++)
	    if (dos_command[i][j] == ':')
	    {
	      strcpy ((char*)lname, (char*)&dos_command[i][j + 1]);
	      if (!lname[0])
	      {
		/* missing filename */
		set_error (34, 0, 0);
		dos_comm_len[i] = 0;
		return (-1);
	      }
	      dos_command[i][j + 1] = 0;
	      dos_comm_len[i] = j;
	      break;
	    }
	  if (!lname[0])
	  {
	    /* no colon, so its all filename */
	    strcpy ((char*)lname, (char*)&dos_command[i][4]);
	    dos_command[i][4] = ':';
	    dos_command[i][5] = 0;
	  }
	  /* find out about host filesystem */
	  if (fs64_parse_path (&dos_command[i][4], path, &par, &dt, &ds))
	  {
	    /* fs64_parse_filespec will have set the error */
	    dos_comm_len[i] = 0;
	    return (-1);
	  }
	  debug_msg ("Md: create [%s] in [%s]\n", lname, path);
	  /* create a fs64_filesystem */
	  if (fs_pathtofilesystem (&fs, path))
	  {
	    /* fs_pathtofilesystem() will have set the error */
	    debug_msg ("Could not make file system\n");
	    return (-1);
	  }
	  /* ensure host media is suitable */
	  switch (fs.media)
	  {
	  case media_D64:
	  case media_D71:
	  case media_D81:
	  case media_DHD:
	    /* 78,recursive filesystem,00,00 */
	    set_error (78, 0, 0);
	    return (-1);
	    break;
	  case media_NET:
	  case media_LNX:
	  case media_T64:
	    /* 76,MEDIA TYPE MISMATCH,00,00 */
	    set_error (76, 0, 0);
	    return (-1);
	    break;
	  case media_UFS:
	    /* bingo! */
	    break;
	  default:
	    /* 76,MEDIA TYPE MISMATCH,00,00 */
	    set_error (76, 0, 0);
	    return (-1);
	  }
	  /* ensure sufficient space */
	  if (fs64_blocksfree (&fs) < blocks)
	  {
	    /* 52,file too large,00,00 */
	    set_error (52, 0, 0);
	    return (-1);
	  }
	  /* okey.. create a new disk image, with the given name
	     (use shortname() to resolve) */
	  switch (media)
	  {
	  case media_D64:
	    strcpy ((char*)ext, ".d64");
	    break;
	  case media_D71:
	    strcpy ((char*)ext, ".d71");
	    break;
	  case media_D81:
	    strcpy ((char*)ext, ".d81");
	    break;
	  case media_DHD:
	    strcpy ((char*)ext, ".dhd");
	    break;
	  default:
	    set_error (38, 0, 0);
	    return (-1);
	  }
	  /* filter crusty chars */
	  for (k = 0; k < (int)strlen (lname); k++)
	    switch (lname[k])
	    {
	    case ',':
	    //case '.':
	    //case '+':
	    case '/':
	    case '\\':
	    case '*':
	    case '?':
	    case ':':
	    case ';':
	    case '~':
	      set_error (33, 0, 0);
	      dos_comm_len[i] = 0;
	      return (-1);
	    default:
		  break;
	    }
	  strcpy ((char*)sname, (char*)lname);
	  sprintf ((char*)path, "%s%s%s", path, sname, ext);
	  debug_msg ("Md: create [%s] of %d blocks\n", path, blocks);
	  /* create physical file */
	  fs.media = media;
	  if ((fs.fsfile = fopen ((char*)path, "r")) != NULL)
	  {
	    /* already exists */
	    fclose (fs.fsfile);
	    fs.fsfile = 0;
	    debug_msg ("Dir exists\n");
	    set_error (63, 0, 0);
	    dos_comm_len[i] = 0;
	    return (-1);
	  }
	  if ((fs.fsfile = fopen ((char*)path, "w+")) == NULL)
	  {
	    /* could not open new file system */
	    debug_msg ("Could not open new file system\n");
	    set_error (74, 0, 0);
	    dos_comm_len[i] = 0;
	    return (-1);
	  }
	  else
	  {
	    if (media == media_DHD)
	    {
	      /* write DHD info block */
	      uchar temp[256] =
	      {0};
	      int i;
	      sprintf ((char*)temp, "DHD %02x TRACKS\nPRG [64NET/2 v00.01 ALPHA            ]\n%c%c",
		       size, 4, size);
	      for (i = 0; i < 256; i++)
		fputc (temp[i], fs.fsfile);
	    }
	  }
	  fclose (fs.fsfile);
	  fs.fsfile = 0;

	  switch (fs.media)
	  {
	  case media_D64:
	  case media_D71:
	  case media_D81:
	  case media_DHD:
	    {
	      /* create file system */
	      if (fs_pathtofilesystem (&fs, path))
	      {
		dos_comm_len[i] = 0;
		return (-1);
	      }
	      /* format it! */
	      debug_msg ("Format please!\n");
	      if (fs_dxx_format (&fs, lname, (uchar*)"01"))
	      {
		dos_comm_len[i] = 0;
		fclose (fs.fsfile);
		fs.fsfile = 0;
		return (-1);
	      }
	      break;
	    }
	  default:
	    {
	      set_error (38, 0, 0);
	      dos_comm_len[i] = 0;
	      fclose (fs.fsfile);
	      fs.fsfile = 0;
	      return (-1);
	    }
	  }
	  dos_comm_len[i] = 0;
	  fclose (fs.fsfile);
	  fs.fsfile = 0;
	  return (0);
	  break;
	}
      };
      break;
    };
  case 'N':
    {
      /* Format disk image */
      uchar valcmd[4] = "NEW";
      int par, k, l = 0;
      uchar path[1024];
      /* get partition number (or `alidate' then partition #) */
      /* (j will contain the offset to the partition) */
      for (j = 1; dos_command[i][j] == valcmd[j]; j++);
      debug_msg ("Parsing [%s]\n", &dos_command[i][j]);
      /* Format a disk image or filesystem in general */
      for (k = j; k < dos_comm_len[i]; k++)
	if (dos_command[i][k] == ':')
	{
	  l = dos_command[i][k + 1];
	  dos_command[i][k + 1] = 0;
	  break;
	}
      if (fs64_parse_path (&dos_command[i][j], path, &par, &dt, &ds))
      {
	/* fs64_parse_filespec will have set the error */
	dos_comm_len[i] = 0;
	return (-1);
      }
      dos_command[i][k + 1] = l;
      debug_msg ("Format: Path [%s] par:%d\n", path, par);
      id[0] = 0;
      name[0] = 0;
      for (j = k + 1; j < dos_comm_len[i]; j++)
	if (dos_command[i][j] != ',')
	  sprintf ((char*)name, "%s%c", name, dos_command[i][j]);
	else
	{
	  dos_command[i][j + 3] = 0;
	  strcpy ((char*)id, (char*)&dos_command[i][j + 1]);
	  if (!id[1])
	    id[1] = 0xa0;
	  break;
	}
      name[16] = 0;
      debug_msg ("Name/id: [%s][%s]\n", name, id);

      {
	/* construct filesystem (or abort) */
	int mt = fs64_mediatype (path);
	switch (mt)
	{
	case media_D64:
	case media_D71:
	case media_D81:
	case media_DHD:
	  {
	    /* disk image */
	    fs64_filesystem fs;
	    fs.fsfile = 0;
	    strcpy ((char*)fs.fspath, (char*)path);
	    fs.media = mt;
	    switch (mt)
	    {
	    case media_D64:
	      fs.dirtrack = 18;
	      fs.dirsector = 0;
	      break;
	    case media_D71:
	      fs.dirtrack = 18;
	      fs.dirsector = 0;
	      break;
	    case media_D81:
	      fs.dirtrack = 40;
	      fs.dirsector = 0;
	      break;
	    case media_DHD:
	      fs.dirtrack = 1;
	      fs.dirsector = 1;
	      break;
	    }
	    if ((fs.fsfile = fopen ((char*)path, "r+")) == NULL)
	    {
	      set_error (74, 0, 0);
	      dos_comm_len[i] = 0;
	      return (-1);
	    }
	    /* format */
	    if (fs_dxx_format (&fs, name, id))
	    {
	      /* gark! */
	      dos_comm_len[i] = 0;
	      return (-1);
	    }
	    else
	    {
	      /* all done */
	      dos_comm_len[i] = 0;
	      set_error (0, 0, 0);
	      return (0);
	    }
	    break;
	  }			/* case media_D?? */
	default:
	  /* 76,MEDIA TYPE MISMATCH,00,00 */
	  set_error (76, 0, 0);
	  dos_comm_len[i] = 0;
	  return (-1);
	}			/* switch(mt) */
      }
      break;
    }
  case 118:
  case 214:			/* shift-V (both c64 codes) */
    {
      /* validate with purge */
      uchar valcmd[9] = "VALIDATE";
      int par;
      uchar path[1024];
      /* get partition number (or `alidate' then partition #) */
      /* (j will contain the offset to the partition) */
      for (j = 1; dos_command[i][j] == valcmd[j]; j++);
      debug_msg ("Parsing [%s]\n", &dos_command[i][j]);
      if (fs64_parse_path (&dos_command[i][j], path, &par, &dt, &ds))
      {
	/* fs64_parse_filespec will have set the error */
	dos_comm_len[i] = 0;
	return (-1);
      }

      debug_msg ("Validate: Path [%s] par:%d\n", path, par);

      {
	/* construct filesystem (or abort) */
	int mt = fs64_mediatype (path);
	switch (mt)
	{
	case media_D64:
	case media_D71:
	case media_D81:
	case media_DHD:
	  {
	    /* disk image */
	    fs64_filesystem fs;
	    fs.fsfile = 0;
	    strcpy ((char*)fs.fspath, (char*)path);
	    fs.media = mt;
	    switch (mt)
	    {
	    case media_D64:
	      fs.dirtrack = 18;
	      fs.dirsector = 0;
	      break;
	    case media_D71:
	      fs.dirtrack = 18;
	      fs.dirsector = 0;
	      break;
	    case media_D81:
	      fs.dirtrack = 40;
	      fs.dirsector = 0;
	      break;
	    case media_DHD:
	      fs.dirtrack = 1;
	      fs.dirsector = 1;
	      break;
	    }
	    if ((fs.fsfile = fopen ((char*)path, "r+")) == NULL)
	    {
	      set_error (74, 0, 0);
	      dos_comm_len[i] = 0;
	      return (-1);
	    }
	    /* validate (plus error correction) */
	    if (fs_dxx_validate (&fs, 1))
	    {
	      /* gark! */
	      dos_comm_len[i] = 0;
	      return (-1);
	    }
	    else
	    {
	      /* all done */
	      dos_comm_len[i] = 0;
	      return (0);
	    }
	    break;
	  }			/* case media_D?? */
	default:
	  /* 76,MEDIA TYPE MISMATCH,00,00 */
	  set_error (76, 0, 0);
	  dos_comm_len[i] = 0;
	  return (-1);
	}			/* switch(mt) */
      }
      break;
    }
  case 'V':
    {
      /* validate */
      uchar valcmd[9] = "VALIDATE";
      int par;
      uchar path[1024];
      /* get partition number (or `alidate' then partition #) */
      /* (j will contain the offset to the partition) */
      for (j = 1; dos_command[i][j] == valcmd[j]; j++);
      debug_msg ("Parsing [%s]\n", &dos_command[i][j]);
      if (fs64_parse_path (&dos_command[i][j], path, &par, &dt, &ds))
      {
	/* fs64_parse_filespec will have set the error */
	dos_comm_len[i] = 0;
	return (-1);
      }

      debug_msg ("Validate: Path [%s] par:%d\n", path, par);

      {
	/* construct filesystem (or abort) */
	int mt = fs64_mediatype (path);
	switch (mt)
	{
	case media_D64:
	case media_D71:
	case media_D81:
	case media_DHD:
	  {
	    /* disk image */
	    fs64_filesystem fs;
	    fs.fsfile = 0;
	    strcpy ((char*)fs.fspath, (char*)path);
	    fs.media = mt;
	    switch (mt)
	    {
	    case media_D64:
	      fs.dirtrack = 18;
	      fs.dirsector = 0;
	      break;
	    case media_D71:
	      fs.dirtrack = 18;
	      fs.dirsector = 0;
	      break;
	    case media_D81:
	      fs.dirtrack = 40;
	      fs.dirsector = 0;
	      break;
	    case media_DHD:
	      fs.dirtrack = 1;
	      fs.dirsector = 1;
	      break;
	    }
	    if ((fs.fsfile = fopen ((char*)path, "r+")) == NULL)
	    {
	      set_error (74, 0, 0);
	      dos_comm_len[i] = 0;
	      return (-1);
	    }
	    /* validate (no error correction) */
	    if (fs_dxx_validate (&fs, 0))
	    {
	      /* gark! */
	      dos_comm_len[i] = 0;
	      return (-1);
	    }
	    else
	    {
	      /* all done */
	      dos_comm_len[i] = 0;
	      return (0);
	    }
	    break;
	  }			/* case media_D?? */
	default:
	  /* 76,MEDIA TYPE MISMATCH,00,00 */
	  set_error (76, 0, 0);
	  dos_comm_len[i] = 0;
	  return (-1);
	}			/* switch(mt) */
      }
      break;
    }
  case 'I':
    /* soft reset drive */
    set_error (0, 0, 0);
    dos_comm_len[i] = 0;
    return (0);
    break;
  case 'U':
    {
      /* Ux disk commands, eg reset, read sector, write sector */
      switch (dos_command[i][1])
      {
      case '1':
      case 'A':
	rv = dos_u1 (dos_command[i], dos_comm_len[i], i);
	dos_comm_len[i] = 0;
	dos_command[i][0] = 0;
	return (rv);
      case '2':
      case 'B':
	/* sector-write */
	/* unimplemented */
	set_error (38, 0, 0);
	dos_comm_len[i] = 0;
	return (0);
      case '3':
      case 'C':
	/* JMP $0500 */
	/* unimplemented */
	set_error (38, 0, 0);
	dos_comm_len[i] = 0;
	return (0);
      case '4':
      case 'D':
	/* JMP $0503 */
	/* unimplemented */
	set_error (38, 0, 0);
	dos_comm_len[i] = 0;
	return (0);
      case '5':
      case 'E':
	/* JMP $0506 */
	/* unimplemented */
	set_error (38, 0, 0);
	dos_comm_len[i] = 0;
	return (0);
      case '6':
      case 'F':
	/* JMP $0509 */
	/* unimplemented */
	set_error (38, 0, 0);
	dos_comm_len[i] = 0;
	return (0);
      case '7':
      case 'G':
	/* JMP $050C */
	/* unimplemented */
	set_error (38, 0, 0);
	dos_comm_len[i] = 0;
	return (0);
      case '8':
      case 'H':
	/* JMP $050F */
	/* unimplemented */
	set_error (38, 0, 0);
	dos_comm_len[i] = 0;
	return (0);
      case '9':
      case 'I':
	/* soft-reset (does nothing) */
	set_error (0, 0, 0);
	dos_comm_len[i] = 0;
	return (0);
      case 'J':
      case ':':
	/* hard-reset */
	reset_drive ();
	dos_comm_len[i] = 0;
	return (0);
      default:
	set_error (30, 0, 0);
	dos_comm_len[i] = 0;
	return (0);
      }				/* end of Ux commands */
    }
  case 'C':
    {
      /* CD,CP etc */
      switch (dos_command[i][1])
      {
      case 'D':
	{
	  /* CD - change subdirectories */
	  /* ALGORITHM (revised):

	     1. Is it a "pwd" ("CD")
	     2. Change : to / and post-pend a : 
	     3. fs64_parse_partition it (like for open etc)
	   */

	  /* get rid of trailing CR's */
	  j = dos_comm_len[i] - 1;
	  while (dos_command[i][j] == 0x0d)
	  {
	    dos_command[i][j] = 0;
	    dos_comm_len[i] -= 1;
	    j--;
	  }

	  if (dos_comm_len[i] == 2)
	  {
	    /* return current dir in status */
		  //strcpy((char*)fname,(char*)name);
		  //petscii2ascii(fname,strlen(fname));
				  
		strcpy((char*)temp,(char*)curr_dir[i][curr_par[i]]);
		start=strlen((char*)partn_dirs[i][curr_par[i]]);
		path[0]='/';
		for(a=start;a<strlen(temp);a++) {
			path[a-start+1]=temp[a];
		}
		path[a-start+1]='\0';
		ascii2petscii(path,strlen(path));
		printf((char*)path);
		printf("\n");
	    //sprintf ((char*)temp, "%02d,%s,%02d,%02d\r",0, (char*) ascii2petscii(cd,strlen(cd)), 0, 0);
	    sprintf ((char*)temp, "%02d,%s,%02d,%02d\r",0, path, 0, 0);
	//sprintf ((char*)temp, "%02d,%s,%02d,%02d\r",0, ascii2petscii((uchar *) curr_dir[i][curr_par[i]],strlen((uchar *) curr_dir[i][curr_par[i]])), 0, 0);
	    set_drive_status (temp, strlen (temp));
	    dos_comm_len[i] = 0;
	    return (0);
	  }

	  par = 0;
	  j = dos_comm_len[i] - 1;
	  for (k = 2; k <= j; k++)
	    switch (dos_command[i][k])
	    {
	    case ':':
	      /* change : to / */
	      dos_command[i][k] = '/';
	      k += 0;
	      j = 0;
	      break;
	    case '/':
	      /* partition before / 
	         (ie no :, so same as for :, but no need to alter */
	      k += 0;
	      j = 0;
	      break;
	    case '_':
	      /* partition before <- 
	         Dont advance k, as <- is the entire path */
	      k--;
	      j = 0;
	      break;
	    case '1':
	    case '2':
	    case '3':
	    case '4':
	    case '5':
	    case '6':
	    case '7':
	    case '8':
	    case '9':
	    case '0':
	      /* digit for partition */
	      par *= 10;
	      par += dos_command[i][k] - 0x30;
	      break;
	    default:
	      /* bad char in CD */
	      set_error (33, 0, 0);
	      dos_comm_len[i] = 0;
	      return (-1);
	    }
	  j = dos_comm_len[i];
	  dos_command[i][j] = 0;

	  debug_msg ("Par: %d, Path [%s]\n", par, &dos_command[i][k]);

	  /* step 2 - fs64_parse_partitions */
	  strcpy ((char*)path, (char*)&dos_command[i][k]);
	  sprintf ((char*)partition, "%d", par);
	  if (fs64_resolve_partition (partition, path, &dt, &ds))
	    /* parse_filespec will have set the error */
	  {
	    dos_comm_len[i] = 0;
	    return (-1);
	  }
	  if (!par) par = curr_par[i];
	  debug_msg ("Parsed path: [%d][%s]\n", par, path);
	  if (curr_dir[i][par]) free (curr_dir[i][par]);
	  curr_dir[i][par] = (uchar *) malloc (strlen (path) + 1);
	  strcpy ((char*)curr_dir[i][par], (char*)path);
	  /* and update dir block */
	  curr_dirtracks[i][par] = dt;
	  curr_dirsectors[i][par] = ds;
	  set_error (0, 0, 0);
	  dos_comm_len[i] = 0;
	  return (0);
	}			/* end of CD */
      case 'P':
      case 'p':
	/* change current partition */
	if (dos_command[i][1] == 'p')
	{
	  /* chr$ version of CP */
	  j = dos_command[i][2];
	}
	else
	{
	  if (dos_command[i][2] == ':')
	    /* skip colon */
	    j = (int)(atof (&dos_command[i][3]));
	  else
	    j = (int)(atof (&dos_command[i][2]));
	}
	if (j == 0)
	{
	  /* only show current partition */
	  set_error (2, curr_par[i], 0);
	}
	else
	{
	  if (partn_dirs[i][j])
	  {
	    /* partition exists */
	    curr_par[i] = j;
	    set_error (2, j, 0);
	  }
	  else
	    /* no such partition */
	    set_error (77, j, 0);
	}			/* if (j==0) (are we getting or setting partition) */
	dos_comm_len[i] = 0;
	return (0);
	break;
      case 'O':
	/* COPY ?? */
	/* fallthough to 'C:' */
      case ':':
      case '0':
      case '1':
      case '2':
      case '3':
      case '4':
      case '5':
      case '6':
      case '7':
      case '8':
      case '9':
	/* C: or Cn: means copy */
	set_error (38, 0, 0);	/* unimplemented */
	break;
      default:
	/* unknown Cx command */
	set_error (30, 0, 0);
	dos_comm_len[i] = 0;
	return (0);
	break;
      }				/* end of C..... command dispatch */
    }				/* end case 'c' */
    break;
  case 'S':
	{ int k;
	    for (k=0;(k<dos_comm_len[i])&&(dos_command[i][k]!=':');k++);
	    if (k==dos_comm_len[i]) {
		set_error (30, 0, 0);
		dos_comm_len[i] = 0;
		return (1);
	    }
	    fs64_scratchfile_g(&dos_command[i][k+1]);
	    dos_comm_len[i] = 0;
	    return (0);
	}
  default:
    /* unknown command */
    set_error (31, 0, 0);
    dos_comm_len[i] = 0;
    return (0);
    break;
  }				/* end of master command dispatch switch */

  /* generic disk command error */
  set_error (30, 0, 0);
  dos_comm_len[i] = 0;
  return (0);

}
Пример #14
0
void *SendHeartRun(void *arg)
{
  pthread_detach(pthread_self());


  char intervalOfSendPingREQ = 0;
  char intervalOfSendGetTime = 0;
  char intervalOfSendHeart = 0;
  char intervalKeepAlive = MQTT_KEEP_ALIVE / 10;


  _Bool needSendPublish = false;

  while(1)
    {
      debug_msg("5s");
      sleep(5);


      if (deviceModel == AP) {
        debug_msg("current deviceModel is AP");
        continue;
      }

      if (g_isCreated) {
        debug_msg("have created socket and connect to server\n");

        //                debug_msg("before wait semsendheart\n" );
        //                sem_wait(&g_semSendHeart);

        //                debug_msg("after wait semsendheart\n ");
        if (g_isConnected) { /* connected to mqtt server */

          debug_msg("g_isSubscribed = %d\n", g_isSubscribed);
          if (g_isSubscribed) {

            intervalOfSendPingREQ ++;
            intervalOfSendGetTime ++;
            intervalOfSendHeart ++;

            if (intervalOfSendPingREQ > intervalKeepAlive) {

              unsigned char pingREQ[2] = {0};
              pingREQ[0] = 0xC0;
              pingREQ[1] = 0x00;
              sendSocket(pingREQ, 2, "mqtt pingreq");

              intervalOfSendPingREQ = 0;
            }
            /* 120 * 5 = 600s = 1hour, so get current time from topicServer every 1 hour */
            if (intervalOfSendGetTime > 120) {
              intervalOfSendGetTime = 0;
              /* TODO: get time form topicServer */
            }

            if (intervalOfSendHeart > 12) {
              intervalOfSendHeart = 0;
              debug_msg("---");
              sendSocket(mqttHeart, mqttHeartLen, "mqttHeart");
            }

          } else {
            debug_msg("---");
            // is not received suback from server.

            /* so should send mqtt subscribe */
            struct mqttSend *mqtt = malloc(sizeof(struct mqttSend));

            /* set message type */
            mqtt->fixedHeader.messageType = SUBSCRIBE;

            /* set topic filter */
            printf("g_mac len = %d\n", strlen(g_mac));
            int count = LEN_OF_TOPICFILTER;
            int i = 0;

            mqtt->variableHeader.topicFilterArr = (char**)malloc(count * sizeof(char*));

            /* set topic filter length */
            mqtt->variableHeader.i_topicFilterArrCount = count;

            for (i = 0; i < count; i++) {
              unsigned char *topicFilter = malloc(strlen(g_subscribeTopicFilter[i]) + strlen(g_mac) + 1);
              
              bzero(topicFilter, strlen(g_subscribeTopicFilter[i]) + strlen(g_mac) + 1);

              memcpy(topicFilter, g_subscribeTopicFilter[i], strlen(g_subscribeTopicFilter[i]));

              memcpy(topicFilter + strlen(g_subscribeTopicFilter[i]), g_mac, strlen(g_mac));

              printf("topicFilter len = %lu\n", strlen(topicFilter));
              printf("topicFilter = %s\n", topicFilter);
              *(mqtt->variableHeader.topicFilterArr + i) = malloc(strlen(topicFilter) + 1);

              bzero(*(mqtt->variableHeader.topicFilterArr + i), strlen(topicFilter) + 1);

              memcpy(*(mqtt->variableHeader.topicFilterArr + i), topicFilter, strlen(topicFilter));

              free(topicFilter);
            }

            unsigned char *temp = NULL;
            int len = packMessage(mqtt, &temp);

            for (i = 0; i < count; i++) {
              free(*(mqtt->variableHeader.topicFilterArr + i));
            }

            free(mqtt->variableHeader.topicFilterArr);
            free(mqtt);

            printf("publishlen = %d\n", len);
            for (i = 0; i < len; i++) {
              printf("%02X,", temp[i]);
            }

            printf("\n" );

            int ret = sendSocket(temp, len, "mqtt subscribe");
            if (ret == -2) {
              //                            sem_post(&g_semSendHeart); /* for re-send this message */
            } else {
            }

            free(temp);
          }
        } else {
          debug_msg("should send mqtt connect\n");
          // is not received connack from server.

          /* so should send mqtt connect */
          /* send connect message */
          struct mqttSend * mqtt = malloc(sizeof(struct mqttSend));

          mqtt->fixedHeader.messageType = CONNECT;

          mqtt->playLoad.clientID = malloc(LEN_OF_MAC);
          bzero(mqtt->playLoad.clientID, LEN_OF_MAC);
          memcpy(mqtt->playLoad.clientID, g_mac, LEN_OF_MAC - 1);

          unsigned char *temp = NULL;

          int len = packMessage(mqtt, &temp);

          free(mqtt->playLoad.clientID);
          free(mqtt);

          int i = 0;

          printf("len = %d\n", len);
          for (i = 0; i < len; i++) {
            printf("%02X,", temp[i]);
          }
          printf("\n" );

          int ret = sendSocket(temp, len, "mqtt connect"); 
          if (ret == -2) {
            //                        sem_post(&g_semSendHeart); /* to re-send this message */
          } else {

          }
          free(temp);
        }
      } else {
        debug_msg("not create socket, should create it\n");
        // should create socket, and connect to server.

        /* if is reConnect network, then continue */
        if (g_isChecking) {
          debug_msg("--");
          continue;
        } else {
          sem_post(&g_semConnectionCheck);
        } /* end g_isChecking else */
      }  /* end g_isCreated else */
    }
  pthread_exit((void*)0);
}
int runQMake(int argc, char **argv)
{
    // stderr is unbuffered by default, but stdout buffering depends on whether
    // there is a terminal attached. Buffering can make output from stderr and stdout
    // appear out of sync, so force stdout to be unbuffered as well.
    // This is particularly important for things like QtCreator and scripted builds.
    setvbuf(stdout, (char *)NULL, _IONBF, 0);

    // parse command line
    int ret = Option::init(argc, argv);
    if(ret != Option::QMAKE_CMDLINE_SUCCESS) {
        if ((ret & Option::QMAKE_CMDLINE_ERROR) != 0)
            return 1;
        return 0;
    }

    QString oldpwd = qmake_getpwd();
#ifdef Q_WS_WIN
    if(!(oldpwd.length() == 3 && oldpwd[0].isLetter() && oldpwd.endsWith(":/")))
#endif
    {
        if(oldpwd.right(1) != QString(QChar(QDir::separator())))
            oldpwd += QDir::separator();
    }
    Option::output_dir = oldpwd; //for now this is the output dir

    if(Option::output.fileName() != "-") {
        QFileInfo fi(Option::output);
        QString dir;
        if(fi.isDir()) {
            dir = fi.filePath();
        } else {
            QString tmp_dir = fi.path();
            if(!tmp_dir.isEmpty() && QFile::exists(tmp_dir))
                dir = tmp_dir;
        }
        if(!dir.isNull() && dir != ".")
            Option::output_dir = dir;
        if(QDir::isRelativePath(Option::output_dir))
            Option::output_dir.prepend(oldpwd);
        Option::output_dir = QDir::cleanPath(Option::output_dir);
    }

    QMakeProperty prop;
    if(Option::qmake_mode == Option::QMAKE_QUERY_PROPERTY || Option::qmake_mode == Option::QMAKE_SET_PROPERTY)
        return prop.exec() ? 0 : 101;

    QMakeProject project(&prop);
    int exit_val = 0;
    QStringList files;
    if(Option::qmake_mode == Option::QMAKE_GENERATE_PROJECT)
        files << "(*hack*)"; //we don't even use files, but we do the for() body once
    else
        files = Option::mkfile::project_files;
    for(QStringList::Iterator pfile = files.begin(); pfile != files.end(); pfile++) {
        if(Option::qmake_mode == Option::QMAKE_GENERATE_MAKEFILE ||
           Option::qmake_mode == Option::QMAKE_GENERATE_PRL) {
            QString fn = Option::fixPathToLocalOS((*pfile));
            if(!QFile::exists(fn)) {
                fprintf(stderr, "Cannot find file: %s.\n", fn.toLatin1().constData());
                exit_val = 2;
                continue;
            }

            //setup pwd properly
            debug_msg(1, "Resetting dir to: %s", oldpwd.toLatin1().constData());
            qmake_setpwd(oldpwd); //reset the old pwd
            int di = fn.lastIndexOf(QDir::separator());
            if(di != -1) {
                debug_msg(1, "Changing dir to: %s", fn.left(di).toLatin1().constData());
                if(!qmake_setpwd(fn.left(di)))
                    fprintf(stderr, "Cannot find directory: %s\n", fn.left(di).toLatin1().constData());
                fn = fn.right(fn.length() - di - 1);
            }

            // read project..
            if(!project.read(fn)) {
                fprintf(stderr, "Error processing project file: %s\n",
                        fn == "-" ? "(stdin)" : (*pfile).toLatin1().constData());
                exit_val = 3;
                continue;
            }
            if(Option::mkfile::do_preprocess) //no need to create makefile
                continue;
        }

        bool success = true;
        MetaMakefileGenerator *mkfile = MetaMakefileGenerator::createMetaGenerator(&project, QString(), false, &success);
        if (!success)
            exit_val = 3;

        if(mkfile && !mkfile->write(oldpwd)) {
            if(Option::qmake_mode == Option::QMAKE_GENERATE_PROJECT)
                fprintf(stderr, "Unable to generate project file.\n");
            else
                fprintf(stderr, "Unable to generate makefile for: %s\n", (*pfile).toLatin1().constData());
            exit_val = 5;
        }
        delete mkfile;
        mkfile = NULL;
    }
    qmakeClearCaches();
    return exit_val;
}
Пример #16
0
int
Ganglia_metadata_send_real( Ganglia_metric gmetric, Ganglia_udp_send_channels send_channels, char *override_string )
{
  int len, i;
  XDR x;
  char gmetricmsg[GANGLIA_MAX_MESSAGE_LEN];
  Ganglia_metadata_msg msg;
  const apr_array_header_t *arr;
  const apr_table_entry_t *elts;
  const char *spoof = SPOOF;
  apr_pool_t *gm_pool=(apr_pool_t*)gmetric->pool;

  if (myhost[0] == '\0') 
      apr_gethostname( (char*)myhost, APRMAXHOSTLEN+1, gm_pool);

  msg.id = gmetadata_full;
  memcpy( &(msg.Ganglia_metadata_msg_u.gfull.metric), gmetric->msg, sizeof(Ganglia_metadata_message));
  msg.Ganglia_metadata_msg_u.gfull.metric_id.name = apr_pstrdup (gm_pool, gmetric->msg->name);
  debug_msg("  msg.Ganglia_metadata_msg_u.gfull.metric_id.name: %s\n", msg.Ganglia_metadata_msg_u.gfull.metric_id.name);
  if ( override_string != NULL )
    {
      msg.Ganglia_metadata_msg_u.gfull.metric_id.host = apr_pstrdup (gm_pool, (char*)override_string);
      debug_msg("  msg.Ganglia_metadata_msg_u.gfull.metric_id.host: %s\n", msg.Ganglia_metadata_msg_u.gfull.metric_id.host);
      msg.Ganglia_metadata_msg_u.gfull.metric_id.spoof = TRUE;
    }
    else
    {
      msg.Ganglia_metadata_msg_u.gfull.metric_id.host = apr_pstrdup (gm_pool, (char*)myhost);
      debug_msg("  msg.Ganglia_metadata_msg_u.gfull.metric_id.host: %s\n", msg.Ganglia_metadata_msg_u.gfull.metric_id.host);
      msg.Ganglia_metadata_msg_u.gfull.metric_id.spoof = FALSE;
    }

  arr = apr_table_elts(gmetric->extra);
  elts = (const apr_table_entry_t *)arr->elts;
  msg.Ganglia_metadata_msg_u.gfull.metric.metadata.metadata_len = arr->nelts;
  msg.Ganglia_metadata_msg_u.gfull.metric.metadata.metadata_val = 
      (Ganglia_extra_data*)apr_pcalloc(gm_pool, sizeof(Ganglia_extra_data)*arr->nelts);

  /* add all of the metadata to the packet */
  for (i = 0; i < arr->nelts; ++i) {
      if (elts[i].key == NULL)
          continue;

      /* Replace the host name with the spoof host if it exists in the metadata */
      if ((apr_toupper(elts[i].key[0]) == spoof[0]) && strcasecmp(SPOOF_HOST, elts[i].key) == 0) 
        {
          msg.Ganglia_metadata_msg_u.gfull.metric_id.host = apr_pstrdup (gm_pool, elts[i].val);
          msg.Ganglia_metadata_msg_u.gfull.metric_id.spoof = TRUE;
        }
      if ((apr_toupper(elts[i].key[0]) == spoof[0]) && strcasecmp(SPOOF_HEARTBEAT, elts[i].key) == 0) 
        {
          msg.Ganglia_metadata_msg_u.gfull.metric_id.name = apr_pstrdup (gm_pool, "heartbeat");
          msg.Ganglia_metadata_msg_u.gfull.metric.name = msg.Ganglia_metadata_msg_u.gfull.metric_id.name;
          msg.Ganglia_metadata_msg_u.gfull.metric_id.spoof = TRUE;
        }

      msg.Ganglia_metadata_msg_u.gfull.metric.metadata.metadata_val[i].name = 
          apr_pstrdup(gm_pool, elts[i].key);
      msg.Ganglia_metadata_msg_u.gfull.metric.metadata.metadata_val[i].data = 
          apr_pstrdup(gm_pool, elts[i].val);
  }

  /* Send the message */
  xdrmem_create(&x, gmetricmsg, GANGLIA_MAX_MESSAGE_LEN, XDR_ENCODE);
  if(!xdr_Ganglia_metadata_msg(&x, &msg))
    {
      return 1;
    }
  len = xdr_getpos(&x); 
  /* Send the encoded data along...*/
  return Ganglia_udp_send_message( send_channels, gmetricmsg, len);
}
Пример #17
0
int compare(const char *filepath)
{
    char *subpath = pathtrim(filepath);
    debug_msg("Comparing File: %s", filepath);
    file_count++;
    // ignore if no read permission
    if (check_privilege(filepath))
    {
        verbose_msg("Ignore file: %s due to privilege limitation: %s", subpath, strerror(errno));
        return -1;
    }

    struct stat buffer;
    int status;
    status = lstat(filepath, &buffer);
    if (status != 0)
    {
        verbose_msg("Fetch file status failed: $s: %s, Error code: %d", subpath, strerror(errno), errno);
        return -1;
    }

    // find the linked list with the same file size and the same file type
    // st_mode & S_IFMT extract the file type code from a mode value.
    list *ls_search = list_new(buffer.st_size, (unsigned int)buffer.st_mode & S_IFMT);
    debug_msg("Size: %d, type: %u,  status=%d", (int)ls_search->filesize, ls_search->filetype, status);
    // store the file info into the node
    list_node *newfile = node_new(filepath, buffer.st_size);
    // reference man page: http://man7.org/linux/man-pages/man3/tsearch.3.html
    // key points to the item to be searched for. rootp points to a variable which points to the root of the tree.
    list **lsp = (list **)tsearch((void *)ls_search, &tree_root, list_compare);
    // returns a pointer to the newly added item.
    list_node *finded_same; //0 true 1 false
    if (lsp == NULL)
    {
        debug_msg("Append child failed");
        exit(1);
    }
    else
    {
        // Find the same file
        list *rls = *lsp;
        debug_msg("Listinfo Size: %d, type: %d", rls->filesize, rls->filetype);
        if (rls != ls_search)
        {
            // list exists
            debug_msg("A list already exists! Search the item.");
            // wheather the same file is in the list
            finded_same = is_samefile_inlist(rls, newfile);

            // add the item to the existing list
            if (finded_same != NULL)
            {
                debug_msg("Same file found!");
                node_free(newfile);
                char *tmp_subpath = pathtrim(finded_same->filepath);
                printf("%s\t%s\n", tmp_subpath, subpath);
                num_du_files++;
                free(tmp_subpath);
                free(subpath);
            }
            else
            {
                list_additem(rls, newfile);
            }
            list_free(ls_search);
        }
        else
        {
            // list not exist
            list_additem(rls, newfile);
            debug_msg("Created a new list!");
        }
    }
    memLimitCheck();
    return 0;
}
Пример #18
0
static int 
Ganglia_cfg_include(cfg_t *cfg, cfg_opt_t *opt, int argc,
                          const char **argv)
{
    char *fname = (char*)argv[0];
    struct stat statbuf;
    DIR *dir;
    struct dirent *entry;

    if(argc != 1)
    {
        cfg_error(cfg, "wrong number of arguments to cfg_include()");
        return 1;
    }

    if (stat (fname, &statbuf) == 0) 
    {
        return cfg_include(cfg, opt, argc, argv);
    }
    else if (has_wildcard(fname))
    {
        int ret;
        char *path = calloc(strlen(fname) + 1, sizeof(char));
        char *pattern = NULL;
        char *idx = strrchr(fname, '/');
        apr_pool_t *p;
        apr_file_t *ftemp;
        char *dirname = NULL;
        char tn[] = "gmond.tmp.XXXXXX";

        if (idx == NULL) {
            idx = strrchr(fname, '\\');
        }

        if (idx == NULL) {
            strncpy (path, ".", 1);
            pattern = fname;
        }
        else {
            strncpy (path, fname, idx - fname);
            pattern = idx + 1;
        }

        apr_pool_create(&p, NULL);
        if (apr_temp_dir_get((const char**)&dirname, p) != APR_SUCCESS) {
#ifndef LINUX
            cfg_error(cfg, "failed to determine the temp dir");
            apr_pool_destroy(p);
            return 1;
#else
            /*
             * workaround APR BUG46297 by using the POSIX shared memory
             * ramdrive that is available since glibc 2.2
             */
            dirname = apr_psprintf(p, "%s", "/dev/shm");
#endif
        }
        dirname = apr_psprintf(p, "%s/%s", dirname, tn);

        if (apr_file_mktemp(&ftemp, dirname, 
                            APR_CREATE | APR_READ | APR_WRITE | APR_DELONCLOSE, 
                            p) != APR_SUCCESS) {
            cfg_error(cfg, "unable to create a temporary file %s", dirname);
            apr_pool_destroy(p);
            return 1;
        }

        dir = opendir(path);

        if(dir != NULL){
            while((entry = readdir(dir)) != NULL) {
                ret = fnmatch(pattern, entry->d_name, 
                              FNM_PATHNAME|FNM_PERIOD);
                if (ret == 0) {
                    char *newpath, *line;

                    newpath = apr_psprintf (p, "%s/%s", path, entry->d_name);
                    line = apr_pstrcat(p, "include ('", newpath, "')\n", NULL);
                    apr_file_puts(line, ftemp);
                }
            }
            closedir(dir);
            free (path);

            argv[0] = dirname;
            if (cfg_include(cfg, opt, argc, argv))
                cfg_error(cfg, "failed to process include file %s", fname);
            else
                debug_msg("processed include file %s\n", fname);
        }

        apr_file_close(ftemp);
        apr_pool_destroy(p);

        argv[0] = fname;
    }
    else 
    {
        cfg_error(cfg, "invalid include path");
        return 1;
    }

    return 0;
}
Пример #19
0
static int
push_data_to_carbon( char *graphite_msg)
{

  if (!strcmp(gmetad_config.carbon_protocol, "tcp"))
    {

      int port;
      int carbon_socket;
      struct sockaddr_in server;
      int carbon_timeout ;
      int nbytes;
      struct pollfd carbon_struct_poll;
      int poll_rval;
      int fl;

      if (gmetad_config.carbon_timeout)
          carbon_timeout=gmetad_config.carbon_timeout;
      else
          carbon_timeout = 500;

      if (gmetad_config.carbon_port)
         port=gmetad_config.carbon_port;
      else
         port=2003;

      debug_msg("Carbon Proxy:: sending \'%s\' to %s", graphite_msg, gmetad_config.carbon_server);

          /* Create a socket. */
      carbon_socket = socket (PF_INET, SOCK_STREAM, 0);
      if (carbon_socket < 0)
        {
          err_msg("socket (client): %s", strerror(errno));
          close (carbon_socket);
          return EXIT_FAILURE;
        }

      /* Set the socket to not block */
      fl = fcntl(carbon_socket,F_GETFL,0);
      fcntl(carbon_socket,F_SETFL,fl | O_NONBLOCK);

      /* Connect to the server. */
      init_sockaddr (&server, gmetad_config.carbon_server, port);
      connect (carbon_socket, (struct sockaddr *) &server, sizeof (server));

      /* Start Poll */
       carbon_struct_poll.fd=carbon_socket;
       carbon_struct_poll.events = POLLOUT;
       poll_rval = poll( &carbon_struct_poll, 1, carbon_timeout ); // default timeout .5s

      /* Send data to the server when the socket becomes ready */
      if( poll_rval < 0 ) {
        debug_msg("carbon proxy:: poll() error");
      } else if ( poll_rval == 0 ) {
        debug_msg("carbon proxy:: Timeout connecting to %s",gmetad_config.carbon_server);
      } else {
        if( carbon_struct_poll.revents & POLLOUT ) {
          /* Ready to send data to the server. */
          debug_msg("carbon proxy:: %s is ready to receive",gmetad_config.carbon_server);
          nbytes = write (carbon_socket, graphite_msg, strlen(graphite_msg) + 1);
          if (nbytes < 0) {
            err_msg("write: %s", strerror(errno));
            close(carbon_socket);
            return EXIT_FAILURE;
          }
        } else if ( carbon_struct_poll.revents & POLLHUP ) {
          debug_msg("carbon proxy:: Recvd an RST from %s during transmission",gmetad_config.carbon_server);
         close(carbon_socket);
         return EXIT_FAILURE;
        } else if ( carbon_struct_poll.revents & POLLERR ) {
          debug_msg("carbon proxy:: Recvd an POLLERR from %s during transmission",gmetad_config.carbon_server);
          close(carbon_socket);
          return EXIT_FAILURE;
        }
      }
      close (carbon_socket);
      ganglia_scoreboard_inc(METS_SENT_GRAPHITE);
      ganglia_scoreboard_inc(METS_SENT_ALL);
      return EXIT_SUCCESS;

  } else {

      int nbytes;

      pthread_mutex_lock( &carbon_mutex );
      nbytes = sendto (carbon_udp_socket->sockfd, graphite_msg, strlen(graphite_msg), 0,
                         (struct sockaddr_in*)&carbon_udp_socket->sa, sizeof (struct sockaddr_in));
      pthread_mutex_unlock( &carbon_mutex );

      if (nbytes != strlen(graphite_msg))
      {
             err_msg("sendto socket (client): %s", strerror(errno));
             return EXIT_FAILURE;
      }
      ganglia_scoreboard_inc(METS_SENT_GRAPHITE);
      ganglia_scoreboard_inc(METS_SENT_ALL);
      return EXIT_SUCCESS;
  }
}
Пример #20
0
UINT32   System_OnStrg_UploadFW(UINT32 DevID)
{
    UINT32 m_MemSrc=0;
    UINT32 uiMemSize=0;
    UINT32 m_SectSize = 0;
    //DX_HANDLE pStrgDev = (DX_HANDLE)GxStrg_GetDevice(DevID);
    DX_HANDLE pGxStrgDXH = (DX_HANDLE)GxStrg_GetDevice(DevID);
    //HNVT_STRG pStrg,pWhichObj;
    DX_HANDLE pFSStrgDXH;
    FST_FILE hFile=NULL;
    UINT32 uiSize=0; //FileSize
    INT32 fst_er;
#if (FW_CHECK_METHOD != FW_CHECK_NOCHECK)
    UINT32 uiSizeExt;
    MEMCHECK_PSEUDOSTR Pesudo = {0};
#endif
    FWSRV_ER fws_er;

    //alloc mem
    uiMemSize = 0x1000000; // 16MB
    m_MemSrc = SxCmd_GetTempMem(uiMemSize);


    //if (pStrgDev == 0)
    if (pGxStrgDXH == 0)
    {
        debug_msg("Incorrect storage\r\n");
        return UPDNAND_STS_FW_INVALID_STG;
    }
    //pStrg = (HNVT_STRG)Dx_Getcaps(pStrgDev, STORAGE_CAPS_HANDLE, 0);
    //if (pStrg == 0)
    //{
    //    debug_msg("Incorrect storage\r\n");
    //    return UPDNAND_STS_FW_INVALID_STG;
    //}

    //FileSys_GetStrgObj(&pWhichObj);
    FileSys_GetStrgObj(&pFSStrgDXH);
    //if(pWhichObj != pStrg)
    if(pFSStrgDXH != pGxStrgDXH)
    {
        debug_msg("Incorrect storage\r\n");
        return UPDNAND_STS_FW_INVALID_STG;
    }
    memset(&Cmd,0,sizeof(Cmd));
    Cmd.Idx = FWSRV_CMD_IDX_GET_BLK_SIZE;
    Cmd.Out.pData = &m_SectSize;
    Cmd.Out.uiNumByte = sizeof(m_SectSize);
    Cmd.Prop.bExitCmdFinish = TRUE;
    fws_er = FwSrv_Cmd(&Cmd);
    if(fws_er != FWSRV_ER_OK)
    {
        debug_msg("FW bin write failed\r\n");
        return UPDNAND_STS_FW_WRITE_CHK_ERR;
    }
    uiSize = (UINT32)FileSys_GetFileLen(uiUpdateFWName);

    if((uiSize==0) || (uiSize>uiMemSize))
    {
        debug_msg("FW bin read fail.\r\n");

        return UPDNAND_STS_FW_READ_ERR;
    }
    hFile = FileSys_OpenFile(uiUpdateFWName, FST_OPEN_READ);

    if(hFile != 0)
    {
        fst_er = FileSys_ReadFile(hFile, (UINT8*)m_MemSrc, &uiSize, 0, NULL);
        FileSys_CloseFile(hFile);
        if(fst_er != FST_STA_OK)
        {
            debug_msg("FW bin read fail. 1\r\n");
            return UPDNAND_STS_FW_READ2_ERR;
        }
    }
    else
    {
        debug_msg("FW bin read fail. 2\r\n");
        return UPDNAND_STS_FW_READ2_ERR;
    }

#if (FW_CHECK_METHOD != FW_CHECK_NOCHECK)
    //Pesudo string is appended to Crc & Checksum flow.
    //It is an additional protection key for project.
    //Both two pseudo strings setting must be match exactly
    //  in "FW bin encryption prcoess" & "update FW process" of project.
    //In FW bin encryption process: (see config in MakeOption.txt)
    //  this string is not written to file.
    //In update FW process: (FW update FW, or Loader update FW)
    //  this string is not written to nand.
    Pesudo.uiAddr = m_MemSrc;
    Pesudo.uiLen = uiSize;
    Pesudo.uiMemSize = uiMemSize;
    Pesudo.pPseudoStr = FW_CHECK_PSEUDO_STR;
    uiSizeExt=MemCheck_AddPseudoStr(&Pesudo);
    #if (FW_CHECK_METHOD == FW_CHECK_CRC)
    if(MemCheck_CalcCrcCode(m_MemSrc,uiSizeExt)!=0)
    #else
    if(MemCheck_CalcCheckSum16Bit(m_MemSrc,uiSizeExt)!=0)
    #endif
    {
        debug_msg("FW bin check error\r\n");
        return UPDNAND_STS_FW_READ_CHK_ERR;
    }
#endif

    memset(&Cmd,0,sizeof(Cmd));
    Buf.uiAddr = m_MemSrc;
    Buf.uiSize = (uiSize+(m_SectSize-1))&(~(m_SectSize-1));
    Cmd.Idx = FWSRV_CMD_IDX_FW_WRITE;
    Cmd.In.pData = &Buf;
    Cmd.In.uiNumByte = sizeof(Buf);
    Cmd.Prop.bExitCmdFinish = TRUE;
    fws_er = FwSrv_Cmd(&Cmd);
    if(fws_er != FWSRV_ER_OK)
    {
        debug_msg("FW bin write failed\r\n");
        return UPDNAND_STS_FW_WRITE_CHK_ERR;
    }

    return UPDNAND_STS_FW_OK;
}
Пример #21
0
bool QMakeSourceFileInfo::findDeps(SourceFile *file)
{
    if(file->dep_checked || file->type == TYPE_UNKNOWN)
        return true;
    files_changed = true;
    file->dep_checked = true;

    struct stat fst;
    char *buffer = 0;
    int buffer_len = 0;
    {
        int fd;
#if defined(_MSC_VER) && _MSC_VER >= 1400
        if (_sopen_s(&fd, fixPathForFile(file->file, true).local().toLatin1().constData(),
            _O_RDONLY, _SH_DENYNO, _S_IREAD) != 0)
            fd = -1;
#else
        fd = open(fixPathForFile(file->file, true).local().toLatin1().constData(), O_RDONLY);
#endif
        if(fd == -1 || fstat(fd, &fst) || S_ISDIR(fst.st_mode))
            return false;
        buffer = getBuffer(fst.st_size);
        for(int have_read = 0;
            (have_read = QT_READ(fd, buffer + buffer_len, fst.st_size - buffer_len));
            buffer_len += have_read);
        QT_CLOSE(fd);
    }
    if(!buffer)
        return false;
    if(!file->deps)
        file->deps = new SourceDependChildren;

    int line_count = 1;

    for(int x = 0; x < buffer_len; ++x) {
        bool try_local = true;
        char *inc = 0;
        if(file->type == QMakeSourceFileInfo::TYPE_UI) {
            // skip whitespaces
            while(x < buffer_len && (*(buffer+x) == ' ' || *(buffer+x) == '\t'))
                ++x;
            if(*(buffer + x) == '<') {
                ++x;
                if(buffer_len >= x + 12 && !strncmp(buffer + x, "includehint", 11) &&
                   (*(buffer + x + 11) == ' ' || *(buffer + x + 11) == '>')) {
                    for(x += 11; *(buffer + x) != '>'; ++x);
                    int inc_len = 0;
                    for(x += 1 ; *(buffer + x + inc_len) != '<'; ++inc_len);
                    *(buffer + x + inc_len) = '\0';
                    inc = buffer + x;
                } else if(buffer_len >= x + 13 && !strncmp(buffer + x, "customwidget", 12) &&
                          (*(buffer + x + 12) == ' ' || *(buffer + x + 12) == '>')) {
                    for(x += 13; *(buffer + x) != '>'; ++x); //skip up to >
                    while(x < buffer_len) {
                        for(x++; *(buffer + x) != '<'; ++x); //skip up to <
                        x++;
                        if(buffer_len >= x + 7 && !strncmp(buffer+x, "header", 6) &&
                           (*(buffer + x + 6) == ' ' || *(buffer + x + 6) == '>')) {
                            for(x += 7; *(buffer + x) != '>'; ++x); //skip up to >
                            int inc_len = 0;
                            for(x += 1 ; *(buffer + x + inc_len) != '<'; ++inc_len);
                            *(buffer + x + inc_len) = '\0';
                            inc = buffer + x;
                            break;
                        } else if(buffer_len >= x + 14 && !strncmp(buffer+x, "/customwidget", 13) &&
                                  (*(buffer + x + 13) == ' ' || *(buffer + x + 13) == '>')) {
                            x += 14;
                            break;
                        }
                    }
                } else if(buffer_len >= x + 8 && !strncmp(buffer + x, "include", 7) &&
                          (*(buffer + x + 7) == ' ' || *(buffer + x + 7) == '>')) {
                    for(x += 8; *(buffer + x) != '>'; ++x) {
                        if(buffer_len >= x + 9 && *(buffer + x) == 'i' &&
                           !strncmp(buffer + x, "impldecl", 8)) {
                            for(x += 8; *(buffer + x) != '='; ++x);
                            if(*(buffer + x) != '=')
                                continue;
                            for(++x; *(buffer+x) == '\t' || *(buffer+x) == ' '; ++x);
                            char quote = 0;
                            if(*(buffer+x) == '\'' || *(buffer+x) == '"') {
                                quote = *(buffer + x);
                                ++x;
                            }
                            int val_len;
                            for(val_len = 0; true; ++val_len) {
                                if(quote) {
                                    if(*(buffer+x+val_len) == quote)
                                        break;
                                } else if(*(buffer + x + val_len) == '>' ||
                                          *(buffer + x + val_len) == ' ') {
                                    break;
                                }
                            }
//?                            char saved = *(buffer + x + val_len);
                            *(buffer + x + val_len) = '\0';
                            if(!strcmp(buffer+x, "in implementation")) {
                                //### do this
                            }
                        }
                    }
                    int inc_len = 0;
                    for(x += 1 ; *(buffer + x + inc_len) != '<'; ++inc_len);
                    *(buffer + x + inc_len) = '\0';
                    inc = buffer + x;
                }
            }
            //read past new line now..
            for(; x < buffer_len && !qmake_endOfLine(*(buffer + x)); ++x);
            ++line_count;
        } else if(file->type == QMakeSourceFileInfo::TYPE_QRC) {
        } else if(file->type == QMakeSourceFileInfo::TYPE_C) {
            for(int beginning=1; x < buffer_len; ++x) {
                // whitespace comments and line-endings
                for(; x < buffer_len; ++x) {
                    if(*(buffer+x) == ' ' || *(buffer+x) == '\t') {
                        // keep going
                    } else if(*(buffer+x) == '/') {
                        ++x;
                        if(buffer_len >= x) {
                            if(*(buffer+x) == '/') { //c++ style comment
                                for(; x < buffer_len && !qmake_endOfLine(*(buffer + x)); ++x);
                                beginning = 1;
                            } else if(*(buffer+x) == '*') { //c style comment
                                for(++x; x < buffer_len; ++x) {
                                    if(*(buffer+x) == '*') {
                                        if(x < buffer_len-1 && *(buffer + (x+1)) == '/') {
                                            ++x;
                                            break;
                                        }
                                    } else if(qmake_endOfLine(*(buffer+x))) {
                                        ++line_count;
                                    }
                                }
                            }
                        }
                    } else if(qmake_endOfLine(*(buffer+x))) {
                        ++line_count;
                        beginning = 1;
                    } else {
                        break;
                    }
                }

                if(x >= buffer_len)
                    break;

                // preprocessor directive
                if(beginning && *(buffer+x) == '#')
                    break;

                // quoted strings
                if(*(buffer+x) == '\'' || *(buffer+x) == '"') {
                    const char term = *(buffer+(x++));
                    for(; x < buffer_len; ++x) {
                        if(*(buffer+x) == term) {
                            ++x;
                            break;
                        } else if(*(buffer+x) == '\\') {
                            ++x;
                        } else if(qmake_endOfLine(*(buffer+x))) {
                            ++line_count;
                        }
                    }
                }
                beginning = 0;
            }
            if(x >= buffer_len)
                break;

            //got a preprocessor symbol
            ++x;
            while(x < buffer_len) {
                if(*(buffer+x) != ' ' && *(buffer+x) != '\t')
                    break;
                ++x;
            }

            int keyword_len = 0;
            const char *keyword = buffer+x;
            while(x+keyword_len < buffer_len) {
                if(((*(buffer+x+keyword_len) < 'a' || *(buffer+x+keyword_len) > 'z')) &&
                   *(buffer+x+keyword_len) != '_') {
                    for(x+=keyword_len; //skip spaces after keyword
                        x < buffer_len && (*(buffer+x) == ' ' || *(buffer+x) == '\t');
                        x++);
                    break;
                } else if(qmake_endOfLine(*(buffer+x+keyword_len))) {
                    x += keyword_len-1;
                    keyword_len = 0;
                    break;
                }
                keyword_len++;
            }

            if(keyword_len == 7 && !strncmp(keyword, "include", keyword_len)) {
                char term = *(buffer + x);
                if(term == '<') {
                    try_local = false;
                    term = '>';
                } else if(term != '"') { //wtf?
                    continue;
                }
                x++;

                int inc_len;
                for(inc_len = 0; *(buffer + x + inc_len) != term && !qmake_endOfLine(*(buffer + x + inc_len)); ++inc_len);
                *(buffer + x + inc_len) = '\0';
                inc = buffer + x;
                x += inc_len;
            } else if(keyword_len == 13 && !strncmp(keyword, "qmake_warning", keyword_len)) {
                char term = 0;
                if(*(buffer + x) == '"')
                    term = '"';
                if(*(buffer + x) == '\'')
                    term = '\'';
                if(term)
                    x++;

                int msg_len;
                for(msg_len = 0; (term && *(buffer + x + msg_len) != term) &&
                              !qmake_endOfLine(*(buffer + x + msg_len)); ++msg_len);
                *(buffer + x + msg_len) = '\0';
                debug_msg(0, "%s:%d %s -- %s", file->file.local().toLatin1().constData(), line_count, keyword, buffer+x);
                x += msg_len;
            } else if(*(buffer+x) == '\'' || *(buffer+x) == '"') {
                const char term = *(buffer+(x++));
                while(x < buffer_len) {
                    if(*(buffer+x) == term)
                        break;
                    if(*(buffer+x) == '\\') {
                        x+=2;
                    } else {
                        if(qmake_endOfLine(*(buffer+x)))
                            ++line_count;
                        ++x;
                    }
                }
            } else {
                --x;
            }
        }

        if(inc) {
            if(!includes)
                includes = new SourceFiles;
            SourceFile *dep = includes->lookupFile(inc);
            if(!dep) {
                bool exists = false;
                QMakeLocalFileName lfn(inc);
                if(QDir::isRelativePath(lfn.real())) {
                    if(try_local) {
                        QString dir = findFileInfo(file->file).path();
                        if(QDir::isRelativePath(dir))
                            dir.prepend(qmake_getpwd() + "/");
                        if(!dir.endsWith("/"))
                            dir += "/";
                        QMakeLocalFileName f(dir + lfn.local());
                        if(findFileInfo(f).exists()) {
                            lfn = fixPathForFile(f);
                            exists = true;
                        }
                    }
                    if(!exists) { //path lookup
                        for(QList<QMakeLocalFileName>::Iterator it = depdirs.begin(); it != depdirs.end(); ++it) {
                            QMakeLocalFileName f((*it).real() + Option::dir_sep + lfn.real());
                            QFileInfo fi(findFileInfo(f));
                            if(fi.exists() && !fi.isDir()) {
                                lfn = fixPathForFile(f);
                                exists = true;
                                break;
                            }
                        }
                    }
                    if(!exists) { //heuristic lookup
                        lfn = findFileForDep(QMakeLocalFileName(inc), file->file);
                        if((exists = !lfn.isNull()))
                            lfn = fixPathForFile(lfn);
                    }
                } else {
                    exists = QFile::exists(lfn.real());
                }
                if(!lfn.isNull()) {
                    dep = files->lookupFile(lfn);
                    if(!dep) {
                        dep = new SourceFile;
                        dep->file = lfn;
                        dep->type = QMakeSourceFileInfo::TYPE_C;
                        files->addFile(dep);
                        includes->addFile(dep, inc, false);
                    }
                    dep->exists = exists;
                }
            }
            if(dep && dep->file != file->file) {
                dep->included_count++;
                if(dep->exists) {
                    debug_msg(5, "%s:%d Found dependency to %s", file->file.real().toLatin1().constData(),
                              line_count, dep->file.local().toLatin1().constData());
                    file->deps->addChild(dep);
                }
            }
        }
    }
    if(dependencyMode() == Recursive) { //done last because buffer is shared
        for(int i = 0; i < file->deps->used_nodes; i++) {
            if(!file->deps->children[i]->deps)
                findDeps(file->deps->children[i]);
        }
    }
    return true;
}
Пример #22
0
static int
oss_probe_mixer_device(int i, struct oss_device *device)
{
	/* Probe /dev/mixerX, and fill in mixer related parts of device.   */
	/* If we are requested to probe /dev/mixer0, and that file doesn't */
	/* exist, we probe /dev/mixer instead (if that is not a symlink).  */
	/* This is for compatibility with some old Linux distributions,    */
	/* which have a broken /dev.                                       */
	mixer_info	info;
	struct stat	s;
	int		valid_mixer = FALSE;
	int		fd, d;

	sprintf(device->mixer_rdev, "/dev/mixer%d", i);
	fd = open(device->mixer_rdev, O_RDWR);
	if ((fd < 0) && (i == 0)) {
		if ((stat("/dev/mixer", &s) == 0) && !S_ISLNK(s.st_mode)) {
			sprintf(device->mixer_rdev, "/dev/mixer");
			fd = open(device->mixer_rdev, O_RDWR);
		}
	}
	if (fd < 0) {
		/* We can't find a working mixer device - this is not  */
		/* necessarily a problem, some soundcards don't have a */
		/* corresponding mixer device.                         */
		device->name = (char *) xmalloc(17);
		sprintf(device->name, "%s", device->mixer_rdev);
		debug_msg("cannot open %s - %s\n", device->mixer_rdev, strerror(errno));
		memset(device->mixer_rdev, 0, 16);
		memset(device->mixer_wdev, 0, 16);
		return FALSE;
	}
	strncpy(device->mixer_wdev, device->mixer_rdev, 16);

	/* Okay, the mixer device is open. Probe its capabilities... */
	if (ioctl(fd, SOUND_MIXER_INFO, &info) != 0) {
		debug_msg("cannot query mixer capabilities\n");
	} else {
		device->name = (char *) xmalloc(OSS_MAX_NAME_LEN + 6);
		memset(device->name, 0, OSS_MAX_NAME_LEN + 6);
		sprintf(device->name, "OSS: ");
		strncpy(device->name + 5, info.name, OSS_MAX_NAME_LEN);
		valid_mixer = TRUE;
	}

	if (ioctl(fd, SOUND_MIXER_READ_DEVMASK, &device->dev_mask) != 0) {
		debug_msg("cannot query mixer dev mask %s\n", strerror(errno));
		device->dev_mask = 0;
	} else {
		debug_msg("device mask for %s:\n", device->mixer_rdev);
		for (d = 0; d < SOUND_MIXER_NRDEVICES; d++) {
			if (device->dev_mask & (1 << d)) {
				debug_msg("  %2d %s\n", d, oss_mixer_channels[d]);
			}
		}
	}

	if (ioctl(fd, SOUND_MIXER_READ_RECMASK, &device->rec_mask) != 0) {
		debug_msg("cannot query mixer rec mask %s\n", strerror(errno));
		device->rec_mask = 0;
	} else {
		debug_msg("recording mask for %s:\n", device->mixer_rdev);
		for (d = 0; d < SOUND_MIXER_NRDEVICES; d++) {
			if (device->rec_mask & (1 << d)) {
				debug_msg("  %2d %s\n", d, oss_mixer_channels[d]);
			}
		}
	}

	device->mixer_rfd = -1;
	device->mixer_wfd = -1;

	close(fd);
	return valid_mixer;
}
Пример #23
0
/** Find devices on remote host.
  * Create new devices on local virtual bus.
  * \warning Function replaces global usb_busses variable from libusb.
  */
int usb_find_devices(void)
{
   // Get remote fd
   Packet* pkt = pkt_claim();
   int fd = session_get();

   // Create buffer
   pkt_init(pkt, UsbFindDevices);
   pkt_send(pkt, fd);

   // Get number of changes
   int res = 0;
   Iterator it;
   if(pkt_recv(fd, pkt) > 0) {
      pkt_begin(pkt, &it);

      // Get return value
      res = iter_getint(&it);

      // Allocate virtualbus
      struct usb_bus vbus;
      vbus.next = __remote_bus;
      struct usb_bus* rbus = &vbus;

      // Get busses
      while(!iter_end(&it)) {

         // Evaluate
         if(it.type == StructureType) {
            iter_enter(&it);

            // Allocate bus
            if(rbus->next == NULL) {

               // Allocate next item
               struct usb_bus* nbus = malloc(sizeof(struct usb_bus));
               memset(nbus, 0, sizeof(struct usb_bus));
               rbus->next = nbus;
               nbus->prev = rbus;
               rbus = nbus;
            }
            else
               rbus = rbus->next;

            // Read dirname
            strcpy(rbus->dirname, iter_getstr(&it));

            // Read location
            rbus->location = iter_getuint(&it);

            // Read devices
            struct usb_device vdev;
            vdev.next = rbus->devices;
            struct usb_device* dev = &vdev;
            while(it.type == SequenceType) {
               iter_enter(&it);

               // Initialize
               if(dev->next == NULL) {
                  dev->next = malloc(sizeof(struct usb_device));
                  memset(dev->next, 0, sizeof(struct usb_device));
                  dev->next->bus = rbus;
                  if(dev != &vdev)
                     dev->next->prev = dev;
                  if(rbus->devices == NULL)
                     rbus->devices = dev->next;
               }

               dev = dev->next;

               // Read filename
               strcpy(dev->filename, iter_getstr(&it));

               // Read devnum
               dev->devnum = iter_getuint(&it);

               // Read descriptor
               // Apply byte-order conversion for 16/32bit integers
               memcpy(&dev->descriptor, it.val, it.len);
               dev->descriptor.bcdUSB = ntohs(dev->descriptor.bcdUSB);
               dev->descriptor.idVendor = ntohs(dev->descriptor.idVendor);
               dev->descriptor.idProduct = ntohs(dev->descriptor.idProduct);
               dev->descriptor.bcdDevice = ntohs(dev->descriptor.bcdDevice);
               iter_next(&it);

               // Alloc configurations
               unsigned cfgid = 0, cfgnum = dev->descriptor.bNumConfigurations;
               dev->config = NULL;
               if(cfgnum > 0) {
                  dev->config = malloc(cfgnum * sizeof(struct usb_config_descriptor));
                  memset(dev->config, 0, cfgnum * sizeof(struct usb_config_descriptor));
               }

               // Read config
               while(it.type == RawType && cfgid < cfgnum) {
                  struct usb_config_descriptor* cfg = &dev->config[cfgid];
                  ++cfgid;

                  // Ensure struct under/overlap
                  int szlen = sizeof(struct usb_config_descriptor);
                  if(szlen > it.len)
                     szlen = it.len;

                  // Read config and apply byte-order conversion
                  memcpy(cfg, it.val, szlen);
                  cfg->wTotalLength = ntohs(cfg->wTotalLength);

                  // Allocate interfaces
                  cfg->interface = NULL;
                  if(cfg->bNumInterfaces > 0) {
                     cfg->interface = malloc(cfg->bNumInterfaces * sizeof(struct usb_interface));
                  }

                  //! \test Implement usb_device extra interfaces - are they needed?
                  cfg->extralen = 0;
                  cfg->extra = NULL;
                  iter_next(&it);

                  // Load interfaces
                  unsigned i, j, k;
                  for(i = 0; i < cfg->bNumInterfaces; ++i) {
                     struct usb_interface* iface = &cfg->interface[i];

                     // Read altsettings count
                     iface->num_altsetting = iter_getint(&it);

                     // Allocate altsettings
                     if(iface->num_altsetting > 0) {
                        iface->altsetting = malloc(iface->num_altsetting * sizeof(struct usb_interface_descriptor));
                     }

                     // Load altsettings
                     for(j = 0; j < iface->num_altsetting; ++j) {

                        // Ensure struct under/overlap
                        struct usb_interface_descriptor* as = &iface->altsetting[j];
                        int szlen = sizeof(struct usb_interface_descriptor);
                        if(szlen > it.len)
                           szlen = it.len;

                        // Read altsettings - no conversions apply
                        memcpy(as, it.val, szlen);
                        iter_next(&it);

                        // Allocate endpoints
                        as->endpoint = NULL;
                        if(as->bNumEndpoints > 0) {
                           size_t epsize = as->bNumEndpoints * sizeof(struct usb_endpoint_descriptor);
                           as->endpoint = malloc(epsize);
                           memset(as->endpoint, 0, epsize);
                        }

                        // Load endpoints
                        for(k = 0; k < as->bNumEndpoints; ++k) {
                           struct usb_endpoint_descriptor* endpoint = &as->endpoint[k];
                           int szlen = sizeof(struct usb_endpoint_descriptor);
                           if(szlen > it.len)
                              szlen = it.len;

                           // Read endpoint and apply conversion
                           memcpy(endpoint, it.val, szlen);
                           endpoint->wMaxPacketSize = ntohs(endpoint->wMaxPacketSize);
                           iter_next(&it);

                           // Null extra descriptors.
                           endpoint->extralen = 0;
                           endpoint->extra = NULL;
                        }

                        // Read extra interface descriptors
                        as->extralen = as_int(it.val, it.len);
                        iter_next(&it);

                        if(as->extralen > 0){
                            as->extra = malloc(as->extralen);

                            int szlen = as->extralen;
                            if(szlen > it.len)
                                szlen = it.len;

                            memcpy(as->extra, it.val, szlen);
                            iter_next(&it);
                        }
                        else
                            as->extra = NULL;
                     }
                  }
               }

               //log_msg("Bus %s Device %s: ID %04x:%04x", rbus->dirname, dev->filename, dev->descriptor.idVendor, dev->descriptor.idProduct);
            }

            // Free unused devices
            while(dev->next != NULL) {
               struct usb_device* ddev = dev->next;
               debug_msg("deleting device %03d", ddev->devnum);
               dev->next = ddev->next;
               free(ddev);
            }

         }
         else {
            debug_msg("unexpected item identifier 0x%02x", it.type);
            iter_next(&it);
         }
      }

      // Deallocate unnecessary busses
      while(rbus->next != NULL) {
         debug_msg("deleting bus %03d", rbus->next->location);
         struct usb_bus* bus = rbus->next;
         rbus->next = bus->next;
      }

      // Save busses
      if(__remote_bus == NULL) {
         __orig_bus = usb_busses;
         debug_msg("overriding global usb_busses from %p to %p", usb_busses, vbus.next);
      }

      __remote_bus = vbus.next;
      usb_busses = __remote_bus;
   }

   // Return remote result
   pkt_release();
   debug_msg("returned %d", res);
   return res;
}
Пример #24
0
static int
oss_probe_audio_device(int i, struct oss_device *device)
{
	/* Probe /dev/dspX, and fill in mixer related parts of the device. */
	/* If we are requested to probe /dev/dsp0, and that file doesn't   */
	/* exist, we probe /dev/dsp instead (if that is not a symlink).    */
	/* This is for compatibility with some old Linux distributions,    */
	/* which have a broken /dev.                                       */
	struct stat	s;
	int		speed[] = {8000, 11025, 16000, 22050, 32000, 44100, 48000};
        int 		stereo, speed_index, fd;

	sprintf(device->audio_rdev, "/dev/dsp%d", i);
	fd = open(device->audio_rdev, O_RDWR);
	if ((fd < 0) && (i == 0)) {
		if ((stat("/dev/dsp", &s) == 0) && !S_ISLNK(s.st_mode)) {
			sprintf(device->audio_rdev, "/dev/dsp");
			fd = open(device->audio_rdev, O_RDWR);
		}
	}
	if (fd < 0) {
		debug_msg("cannot open %s - %s\n", device->audio_rdev, strerror(errno));
		return FALSE;
	}
	strncpy(device->audio_wdev, device->audio_rdev, 16);

	/* Check if the device is full duplex. This MUST be the first test   */
	/* after the audio device is opened.                                 */
	if (ioctl(fd, SNDCTL_DSP_SETDUPLEX, 0) == -1) {
		debug_msg("testing %s support for full duplex operation: no\n", device->audio_rdev);
		device->duplex = OSS_DUPLEX_HALF;
	} else {
		debug_msg("testing %s support for full duplex operation: yes\n", device->audio_rdev);
		device->duplex = OSS_DUPLEX_FULL;
	}

	/* Check which sampling modes are supported...                       */
	device->num_supported_formats = 0;
	for (speed_index = 0; speed_index < 7; speed_index++) {
                for (stereo = 0; stereo < 2; stereo++) {
			debug_msg("testing %s support for %5dHz %s\n", device->audio_rdev, speed[speed_index], stereo?"stereo":"mono");
                        if (oss_test_mode(fd, speed[speed_index], stereo)) {
				device->supported_formats[device->num_supported_formats].sample_rate = speed[speed_index];
				device->supported_formats[device->num_supported_formats].channels    = stereo + 1;
				device->num_supported_formats++;
			}
                }
        }
	/* Check for OSS version number */

	{
#ifdef OSS_GETVERSION
	    int version = -1;
	    if (ioctl(fd, OSS_GETVERSION, &version) < 0) {
		debug_msg("%s doesn't support OSS_GETVERSION\n",
			  device->audio_rdev);
	    } else {
		int level;
		debug_msg("OSS version is %x\n", version);

		/*
		 * Check to see if we can use the MIXER_RECLEV setting
		 * If we can, this might be an ES1371-based card that uses
		 * RECLEV to adjust input levels.
		 */

		if (ioctl(fd, MIXER_READ(SOUND_MIXER_RECLEV), &level) >= 0) {
		    debug_msg("Can use reclev. \n");
		
		    if (version >= 0x030903) {
			debug_msg("Enabling latemodel opensound\n");
			device->is_latemodel_opensound = 1;
		    }
		}
	    }
#endif
	}

	close(fd);
	device->audio_rfd = -1;
	device->audio_wfd = -1;
	return TRUE;
}
Пример #25
0
int
main ( int argc, char *argv[] )
{
   int rc;
   struct stat struct_stat;
   pthread_t pid;
   pthread_attr_t attr;
   int i, num_sources;
   uid_t gmetad_uid;
   mode_t rrd_umask;
   char * gmetad_username;
   struct passwd *pw;
   gmetad_config_t *c = &gmetad_config;
   apr_interval_time_t sleep_time;
   apr_time_t summary_started, now;
   double random_sleep_factor;
   unsigned int rand_seed;

   rc = apr_initialize();
   if (rc != APR_SUCCESS) {
      return -1;
   }

   /* create a memory pool. */
   apr_pool_create(&global_context, NULL);

   /* Ignore SIGPIPE */
   signal( SIGPIPE, SIG_IGN );

   initialize_scoreboard();

   /* Mark the time this gmetad started */
   started = apr_time_now();

   if (cmdline_parser(argc, argv, &args_info) != 0)
      err_quit("command-line parser error");

   num_sources = number_of_datasources( args_info.conf_arg );
   if(!num_sources)
      {
         err_quit("%s doesn't have any data sources specified", args_info.conf_arg);
      }

   memset(&root, 0, sizeof(root));
   root.id = ROOT_NODE;

   /* Get the real number of data sources later */
   sources = hash_create( num_sources + 10 );
   if (! sources )
      {
         err_quit("Unable to create sources hash\n");
      }

   root.authority = hash_create( num_sources + 10 );
   if (!root.authority)
      {
         err_quit("Unable to create root authority (our grids and clusters) hash\n");
      }

   root.metric_summary = hash_create (DEFAULT_METRICSIZE);
   if (!root.metric_summary)
      {
         err_quit("Unable to create root summary hash");
      }

   parse_config_file ( args_info.conf_arg );
    /* If given, use command line directives over config file ones. */
   if (args_info.debug_given)
      {
         c->debug_level = args_info.debug_arg;
      }
   debug_level = c->debug_level;
   set_debug_msg_level(debug_level);

   /* Setup our default authority pointer if the conf file hasnt yet.
    * Done in the style of hash node strings. */
   if (!root.stringslen)
      {
         gethostname(hostname, HOSTNAMESZ);
         root.authority_ptr = 0;
         sprintf(root.strings, "http://%s/ganglia/", hostname);
         root.stringslen += strlen(root.strings) + 1;
      }

   rand_seed = apr_time_now() * (int)pthread_self();
   for(i = 0; i < root.stringslen; rand_seed = rand_seed * root.strings[i++]);

   /* Debug level 1 is error output only, and no daemonizing. */
   if (!debug_level)
      {
         rrd_umask = c->umask;
         daemon_init (argv[0], 0, rrd_umask);
      }

   if (args_info.pid_file_given)
     {
       update_pidfile (args_info.pid_file_arg);
     }

   /* The rrd_rootdir must be writable by the gmetad process */
   if( c->should_setuid )
      {
         if(! (pw = getpwnam(c->setuid_username)))
            {
               err_sys("Getpwnam error");
            }
         gmetad_uid = pw->pw_uid;
         gmetad_username = c->setuid_username;
      }
   else
      {
         gmetad_uid = getuid();
         if(! (pw = getpwuid(gmetad_uid)))
            {
               err_sys("Getpwnam error");
            } 
         gmetad_username = strdup(pw->pw_name);
      }

   debug_msg("Going to run as user %s", gmetad_username);
   if( c->should_setuid )
      {
         become_a_nobody(c->setuid_username);
      }

   if( c->write_rrds )
      {
         if( stat( c->rrd_rootdir, &struct_stat ) )
            {
                err_sys("Please make sure that %s exists", c->rrd_rootdir);
            }
         if ( struct_stat.st_uid != gmetad_uid )
            {
                err_quit("Please make sure that %s is owned by %s", c->rrd_rootdir, gmetad_username);
            }
         if (! (struct_stat.st_mode & S_IWUSR) )
            {
                err_quit("Please make sure %s has WRITE permission for %s", gmetad_username, c->rrd_rootdir);
            }
      }

   if(debug_level)
      {
         fprintf(stderr,"Sources are ...\n");
         hash_foreach( sources, print_sources, NULL);
      }

#ifdef WITH_MEMCACHED
   if (c->memcached_parameters != NULL)
      {
         memcached_connection_pool = memcached_pool(c->memcached_parameters, strlen(c->memcached_parameters));
      }
#endif /* WITH_MEMCACHED */

   server_socket = g_tcp_socket_server_new( c->xml_port );
   if (server_socket == NULL)
      {
         err_quit("tcp_listen() on xml_port failed");
      }
   debug_msg("xml listening on port %d", c->xml_port);
   
   interactive_socket = g_tcp_socket_server_new( c->interactive_port );
   if (interactive_socket == NULL)
      {
         err_quit("tcp_listen() on interactive_port failed");
      }
   debug_msg("interactive xml listening on port %d", c->interactive_port);

    /* Forward metrics to Graphite using carbon protocol */
    if (c->carbon_server != NULL)
      {
         if (!strcmp(c->carbon_protocol, "udp"))
            {
               carbon_udp_socket = init_carbon_udp_socket (c->carbon_server, c->carbon_port);

               if (carbon_udp_socket == NULL)
                  err_quit("carbon %s socket failed for %s:%d", c->carbon_protocol, c->carbon_server, c->carbon_port);
            }
         debug_msg("carbon forwarding ready to send via %s to %s:%d", c->carbon_protocol, c->carbon_server, c->carbon_port);
      }

#ifdef WITH_RIEMANN
    if (c->riemann_server !=NULL)
      {
         if (!strcmp(c->riemann_protocol, "udp"))
            {
               riemann_udp_socket = init_riemann_udp_socket (c->riemann_server, c->riemann_port);

               if (riemann_udp_socket == NULL)
                  err_quit("[riemann] %s socket failed for %s:%d", c->riemann_protocol, c->riemann_server, c->riemann_port);
            } else if (!strcmp(c->riemann_protocol, "tcp")) {
                riemann_tcp_socket = init_riemann_tcp_socket (c->riemann_server, c->riemann_port);
                if (riemann_tcp_socket == NULL) {
                   riemann_circuit_breaker = RIEMANN_CB_OPEN;
                   riemann_reset_timeout = apr_time_now () + RIEMANN_RETRY_TIMEOUT * APR_USEC_PER_SEC;
                } else {
                   riemann_circuit_breaker = RIEMANN_CB_CLOSED;
                   riemann_failures = 0;
                }
            } else {
                err_quit("ERROR: Riemann protocol must be 'udp' or 'tcp'");
            }
         debug_msg("[riemann] Ganglia configured to forward metrics via %s to %s:%d", c->riemann_protocol, c->riemann_server, c->riemann_port);
      }
#endif /* WITH_RIEMANN */

   /* initialize summary mutex */
   root.sum_finished = (pthread_mutex_t *) 
                          malloc(sizeof(pthread_mutex_t));
   pthread_mutex_init(root.sum_finished, NULL);

   pthread_attr_init( &attr );
   pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_DETACHED );

   /* Spin off the non-interactive server threads. (Half as many as interactive). */
   for (i=0; i < c->server_threads/2; i++)
      pthread_create(&pid, &attr, server_thread, (void*) 0);

   /* Spin off the interactive server threads. */
   for (i=0; i < c->server_threads; i++)
      pthread_create(&pid, &attr, server_thread, (void*) 1);

   hash_foreach( sources, spin_off_the_data_threads, NULL );

   /* A thread to cleanup old metrics and hosts */
   pthread_create(&pid, &attr, cleanup_thread, (void *) NULL);
   debug_msg("cleanup thread has been started");

#ifdef WITH_RIEMANN
   if (!strcmp(c->riemann_protocol, "tcp")) {
      /* A thread to re-poll riemann TCP port if circuit breaker tripped */
      pthread_create(&pid, &attr, circuit_breaker_thread, (void *) NULL);
      debug_msg ("[riemann] circuit breaker thread has been started");
   }
#endif /* WITH_RIEMANN */

    /* Meta data */
   last_metadata = apr_time_now();  //Updating global variable
   for(;;)
      {
         /* Do at a random interval, between 
                 (shortest_step/2) +/- METADATA_SLEEP_RANDOMIZE percent */
         random_sleep_factor = (1 + (METADATA_SLEEP_RANDOMIZE / 50.0) * ((rand_r(&rand_seed) - RAND_MAX/2)/(float)RAND_MAX));
         sleep_time = random_sleep_factor * apr_time_from_sec(c->shortest_step) / 2;
         /* Make sure the sleep time is at least 1 second */
         if(apr_time_sec(apr_time_now() + sleep_time) < (METADATA_MINIMUM_SLEEP + apr_time_sec(apr_time_now())))
            sleep_time += apr_time_from_sec(METADATA_MINIMUM_SLEEP);
         apr_sleep(sleep_time);

         /* Need to be sure root is locked while doing summary */
         pthread_mutex_lock(root.sum_finished);

         summary_started = apr_time_now();
         /* Flush the old values */
         hash_foreach(root.metric_summary, zero_out_summary, NULL);
         root.hosts_up = 0;
         root.hosts_down = 0;

         /* Sum the new values */
         hash_foreach(root.authority, do_root_summary, NULL );

         /* Save them to RRD */
         hash_foreach(root.metric_summary, write_root_summary, NULL);

         /* summary completed */
         pthread_mutex_unlock(root.sum_finished);

         /* Remember our last run */
         now = apr_time_now();
         last_metadata = now;  //Updating global variable
         ganglia_scoreboard_incby(METS_SUMRZ_DURATION, now - summary_started);
      }

   apr_pool_destroy(global_context);

   apr_terminate();
   return 0;
}
Пример #26
0
int
oss_audio_open(audio_desc_t ad, audio_format *ifmt, audio_format *ofmt)
{
	/* Try to open the audio device, returning TRUE if successful. Note  */
	/* that the order in which the device is set up is important: don't  */
	/* reorder this code unless you really know what you're doing.       */
#if 0
	int  	volume   = (100<<8)|100;
#endif
	int  	frag     = 0x7fff0000; 			/* unlimited number of fragments */
	char 	buffer[128];				/* sigh. */
	int	bytes_per_block;

        if (ad < 0 || ad > OSS_MAX_DEVICES) {
                debug_msg("invalid audio descriptor (%d)", ad);
                return FALSE;
        }

	devices[ad].audio_rfd = -1;
	devices[ad].audio_wfd = -1;
	devices[ad].mixer_rfd = -1;
	devices[ad].mixer_wfd = -1;

	switch (devices[ad].duplex) {
		case OSS_DUPLEX_HALF:
			debug_msg("cannot open half duplex devices\n");
			return FALSE;
		case OSS_DUPLEX_FULL:
			/* Open the device, and switch to full duplex mode. */
			assert(strcmp(devices[ad].audio_rdev, devices[ad].audio_wdev) == 0);

			devices[ad].audio_rfd = open(devices[ad].audio_rdev, O_RDWR | O_NDELAY);
			if (devices[ad].audio_rfd == 0) {
				debug_msg("unable to open %s\n", devices[ad].audio_rdev);
				return FALSE;
			}
			devices[ad].audio_wfd = devices[ad].audio_rfd;

			if (ioctl(devices[ad].audio_rfd, SNDCTL_DSP_SETDUPLEX, 0) == -1) {
				debug_msg("device doesn't support full duplex operation\n");
				oss_audio_close(ad);
				return FALSE;
			}

			/* Now open the corresponding mixer device... */
			devices[ad].mixer_rfd = open(devices[ad].mixer_rdev, O_RDWR | O_NDELAY);
			if (devices[ad].mixer_rfd == 0) {
				debug_msg("unable to open %s\n", devices[ad].mixer_rdev);
				oss_audio_close(ad);
				return FALSE;
			}
			devices[ad].mixer_wfd = devices[ad].mixer_rfd;

			break;
		case OSS_DUPLEX_PAIR:
			devices[ad].audio_rfd = open(devices[ad].audio_rdev, O_RDONLY | O_NDELAY);
			if (devices[ad].audio_rfd == 0) {
				debug_msg("unable to open %s\n", devices[ad].audio_rdev);
				return FALSE;
			}

			devices[ad].audio_wfd = open(devices[ad].audio_wdev, O_WRONLY | O_NDELAY);
			if (devices[ad].audio_wfd == 0) {
				debug_msg("unable to open %s\n", devices[ad].audio_wdev);
				return FALSE;
			}

			/* Now open the corresponding mixer device... */
			devices[ad].mixer_rfd = open(devices[ad].mixer_rdev, O_RDWR | O_NDELAY);
			if (devices[ad].mixer_rfd == 0) {
				debug_msg("unable to open %s\n", devices[ad].mixer_rdev);
				oss_audio_close(ad);
				return FALSE;
			}
			devices[ad].mixer_wfd = open(devices[ad].mixer_wdev, O_RDWR | O_NDELAY);
			if (devices[ad].mixer_wfd == 0) {
				debug_msg("unable to open %s\n", devices[ad].mixer_wdev);
				oss_audio_close(ad);
				return FALSE;
			}
			break;
		default:
			debug_msg("invalid duplex mode - this can never happen\n");
			abort();
	}
	
	/* Set 20 ms blocksize - this only modulates read sizes, and hence only has to be done on audio_rfd */
	bytes_per_block = 20 * (ifmt->sample_rate / 1000) * (ifmt->bits_per_sample / 8);
	/* Round to the nearest legal frag size (next power of two lower...) */
	frag |= (int) (log(bytes_per_block)/log(2));
	if ((ioctl(devices[ad].audio_rfd, SNDCTL_DSP_SETFRAGMENT, &frag) == -1)) {
		debug_msg("cannot set fragement size (frag=%x bytes_per_block=%d)\n", frag, bytes_per_block);
	}

	if (!oss_configure_device(devices[ad].audio_rfd, ifmt, ofmt)) {
		oss_audio_close(ad);
		return FALSE;
	}
	if (!oss_configure_device(devices[ad].audio_wfd, ifmt, ofmt)) {
		oss_audio_close(ad);
		return FALSE;
	}

	/* Set global gain/volume to maximum values. This may fail on */
	/* some cards, but shouldn't cause any harm when it does..... */ 

#if 0
	ioctl(devices[ad].mixer_rfd, MIXER_WRITE(SOUND_MIXER_RECLEV), &volume);
	ioctl(devices[ad].mixer_wfd, MIXER_WRITE(SOUND_MIXER_VOLUME), &volume);
#endif
	/* Select microphone input. We can't select output source...  */
	oss_audio_iport_set(ad, iport);
	/* Device driver bug: we must read some data before the ioctl */
	/* to tell us how much data is waiting works....              */
	read(devices[ad].audio_rfd, buffer, 128);	

	return TRUE;
}
Пример #27
0
const char *host_addr6(void)
{
#ifdef HAVE_IPv6
	static char		 hname[MAXHOSTNAMELEN];
	int 			 gai_err, newsock;
	struct addrinfo 	 hints, *ai;
	struct sockaddr_in6 	 local, addr6;
	int len = sizeof(local), result = 0;
	
	newsock=socket(AF_INET6, SOCK_DGRAM,0);
    memset ((char *)&addr6, 0, len);
    addr6.sin6_family = AF_INET6;
#ifdef HAVE_SIN6_LEN
    addr6.sin6_len    = len;
#endif
    bind (newsock, (struct sockaddr *) &addr6, len);
    addr6.sin6_addr = s->addr6;
    addr6.sin6_port = htons (s->rx_port);
    connect (newsock, (struct sockaddr *) &addr6, len);
	
    memset ((char *)&local, 0, len);
	if ((result = getsockname(newsock,(struct sockaddr *)&local, &len)) < 0){
		local.sin6_addr = in6addr_any;
		local.sin6_port = 0;
		debug_msg("getsockname failed\n");
	}
	
	close (newsock);
	
	if (IN6_IS_ADDR_UNSPECIFIED(&local.sin6_addr) || IN6_IS_ADDR_MULTICAST(&local.sin6_addr)) {
		if (gethostname(hname, MAXHOSTNAMELEN) != 0) {
			debug_msg("gethostname failed\n");
			abort();
		}
		
		hints.ai_protocol  = 0;
		hints.ai_flags     = 0;
		hints.ai_family    = AF_INET6;
		hints.ai_socktype  = SOCK_DGRAM;
		hints.ai_addrlen   = 0;
		hints.ai_canonname = NULL;
		hints.ai_addr      = NULL;
		hints.ai_next      = NULL;
		
		if ((gai_err = getaddrinfo(hname, NULL, &hints, &ai))) {
			debug_msg("getaddrinfo: %s: %s\n", hname, gai_strerror(gai_err));
			abort();
		}
		
		if (inet_ntop(AF_INET6, &(((struct sockaddr_in6 *)(ai->ai_addr))->sin6_addr), hname, MAXHOSTNAMELEN) == NULL) {
			debug_msg("inet_ntop: %s: \n", hname);
			abort();
		}
		freeaddrinfo(ai);
		return (const char*)hname;
	}
	if (inet_ntop(AF_INET6, &local.sin6_addr, hname, MAXHOSTNAMELEN) == NULL) {
		debug_msg("inet_ntop: %s: \n", hname);
		abort();
	}
	return (const char*)hname;
#else  /* HAVE_IPv6 */
	//UNUSED(s);
	return "::";	/* The unspecified address... */
#endif /* HAVE_IPv6 */
}
Пример #28
0
void UI_UpdateCfgFile(void)
{
#if 0
    UINT32      uiKeyAct, uiKeyCode;
    FLGPTN     uiFlag;
#endif
    char*       str;
    FST_FILE    pFile;
    UINT32      uiFileSize;
    UINT8       *BgBuf;
    char        *fileName;
    IRECT       Rect = {0, 0, 320, 240};
    BOOL        Ret  =TRUE ;
    ER          erReturn;

    PSTORE_SECTION_HANDLE* pSecHdl; // to save the handle of PStore section

    fileName = "A:\\NTCONFIG.bin";

    FileSys_WaitFinish();
    pFile = FileSys_OpenFile(fileName, FST_OPEN_READ);

    if (pFile == NULL)
    {
        debug_err(("open file error\r\n"));
        Ret  =FALSE;
    }

    uiFileSize = FileSys_GetFileLen(fileName);  // for small page nand
    USE_MSG(("file size = %d\r\n",uiFileSize));

    //if file is null
    if (uiFileSize == 0)
    {
        USE_MSG(("file size is 0\r\n"));
        Ret  =FALSE;
    }

    if (uiFileSize > CFG_MAX_FILESIZE)
    {
        USE_MSG(("file size is bigger = %d\r\n",uiFileSize));
        Ret  =FALSE;
    }

    //get_blk((void *)&BgBuf,  POOL_ID_SICD);
    //rel_blk(POOL_ID_SICD, BgBuf);
    //SysGetSICDAddr((UINT32*)&BgBuf);
    BgBuf = (UINT8 *)OS_GetMempoolAddr(POOL_ID_APP);
    if (FileSys_ReadFile(pFile,BgBuf,&uiFileSize,FST_FLAG_NONE,NULL)!=FST_STA_OK)
    {
        USE_MSG(("file read failed\r\n"));
        Ret  =FALSE;
    }

    FileSys_CloseFile(pFile);

    *BgBuf = LO_BYTE(LO_WORD(uiFileSize));
    *(BgBuf+1) = HI_BYTE(LO_WORD(uiFileSize));
    *(BgBuf+2) = LO_BYTE(HI_WORD(uiFileSize));
    *(BgBuf+3) = HI_BYTE(HI_WORD(uiFileSize));

    //PStore_EnablePS();
    pSecHdl = PStore_OpenSection(PS_BG_CFG, PS_RDWR | PS_CREATE);

    if (pSecHdl == E_PS_SECHDLER)
    {
        debug_err(("Section open fail\r\n"));
        PStore_CloseSection(pSecHdl);
        //PStore_DisablePS();
        Ret  =FALSE;
    }

    erReturn = PStore_WriteSection(BgBuf, 0, SYSPARAM_SYSFLAG_LEN, pSecHdl);

    PStore_CloseSection(pSecHdl);

    if (erReturn != E_PS_OK)
    {
        debug_err(("PStore program error\r\n"));
        Ret  =FALSE;
    }


    Cal_FillRect(&Rect, _OSD_INDEX_BLACK);

    Rect.x   = 56;
    Rect.y   = 108;
    Rect.w   = 212;
    Rect.h   = 24;

    if (Ret  == FALSE)
    {
        str =  "Update Cfg file error";
        Cal_ShowStringByColor(str, &Rect, _OSD_INDEX_YELLOW, _OSD_INDEX_BLACK);
    }else
    {
        str = "Update Cfg file ok";
        Cal_ShowStringByColor(str, &Rect, _OSD_INDEX_YELLOW, _OSD_INDEX_BLACK);
    }

    Delay_DelayMs(1000);

    if (Ret)
    {
       System_PowerOff(SYS_POWEROFF_NORMAL);
    }

#if 0

    clr_flg(FLG_ID_CALIBRATION, 0xffffffff);
    while (1)
    {
        wai_flg(&uiFlag, FLG_ID_CALIBRATION, 0xffffffff, TWF_ORW | TWF_CLR);

        debug_msg("^GuiFlag:%x\r\n",uiFlag);
        if (uiFlag)
            break;
    }
#else
    Delay_DelayMs(1500);
#endif
}
Пример #29
0
void update_bc(network *net, double time) {
  double dt = 1000./(net->npcent);
  double Beta; 
  //  Update of BC below
  update_compressors(net, time);
  update_demands(net, time);
  double flux_residual = 0.;
  //double Sinc;
  for (int j = 0; j < net->nnodes; j++) {
    n_k = net->knot[j];
    n_k->P = 0.;//-(net->c)*n_k->D;
    n_k->mult = 0.;
    sprintf(dmsg,"Doing Node %p:\n", n_k);
    debug_msg(dmsg);
    //printf("Node %02d:\t", j);
    for (int l = 0; l < n_k->adj_n; l++) {
      p_k = n_k->adj_p[l];
      if (p_k->left == n_k) {            	      // means left side of pipe p_k is connected to node j
        n_k->P += p_k->Wb_l*0.25*pi*(p_k->d*p_k->d);  // new accounts for distinct crossections of pipes

	//printf("found pipe %p (left)\t", p_k);

	sprintf(dmsg,"Pipe %p: W* = %.15e\n", p_k, p_k->Wb_l);
	debug_msg(dmsg);
#if 1	
	if (p_k->c_id != NULL) {
		n_k->mult += (p_k->c_id)->cratio*0.25*pi*(p_k->d*p_k->d);
		sprintf(msg, "Compressor %p located in pipe %p \n", p_k->c_id, p_k);
		debug_msg(msg);
	}
	else n_k->mult += 0.25*pi*(p_k->d*p_k->d);
#endif
      } 
      else if ( p_k->right == n_k ) { 		      // means right side of pipe p_k is connected to node j
	n_k->P += p_k->W_r*0.25*pi*(p_k->d*p_k->d);   // new

	//printf("found pipe %p (right)\t Diameter = %.12e\n", p_k, p_k->d); exit(1);

	sprintf(dmsg, "Pipe %p: W = %.15e\n", p_k, p_k->W_r);
	debug_msg(dmsg);
	n_k->mult += 0.25*pi*(p_k->d*p_k->d);
      } else {
        err_msg("Error in network construction");
      }
    }
    //printf("Sum Si*Wi = %.16e\nn_k->mult = %.16e\nC = %.16e\n", n_k->P, n_k->mult,(p_k->c_id)->cratio);
    //exit(1);
    sprintf(dmsg,"Current denominator %.15e\n", n_k->mult);
    debug_msg(dmsg);

    
    //unsigned int sim = 3;
    if (j == 0) {
	if (net->LFLAG == 1) {
	  n_k->P = net->P0;
  	  //if (p_k->c_id != NULL) n_k->P = net->P0*(p_k->c_id)->cratio;
	} else {
	  n_k->P = (sq2*n_k->P)/(n_k->mult) + net->F0;  // should derive this again... n_k->P = (sq2*n_k->P + (net->F0))/(n_k->mult);
	}
        /*
        if (sim == 2) {
          double P0 = 1e7;
          double Pval = P0;
          double frq = 0.00174436248289312;

          Pval = P0*exp(144.*1e-9/frq*(1.-cos(1.0*frq*time)));
          n_k->P = Pval;
        } else if (sim == 3) {
	  double A = 10088085.7094053;
	  double B = -88289.1640032395;
	  double frq = 0.00174534439987236;
          double Pval = A;
 	  Pval += B*cos(1.0*frq*time);
 	  n_k->P = Pval;
        }
       */
    } else n_k->P = (sq2*n_k->P - (net->c)*(n_k->D))/(n_k->mult);

    if (j == 1) { 
      if (RFLAG_P_FIXED) {
      /*
 	if (sim == 1) {
          double A1 = 6.40365e+06;
          double B1 = 2.80523e+06;
          double C1 = 324426;
          double D1 = 77302.9;
          double E1 = 22734.1;
          double frq = 0.00174436248289312;

	  double Pval = A1;
          Pval += -B1*cos(1.0*frq*time);
          Pval += -C1*cos(2.0*frq*time);  
          Pval += -D1*cos(3.0*frq*time);  
          Pval += -E1*cos(4.0*frq*time);  
          n_k->P = Pval;
        } else if (sim == 2) {
          double A1 = 3156065.06937776;
          double B1 = 277911.435298177;
          double C1 = -6718.98478372491;
          double D1 = 65.6104975076953;
          double frq = 0.00174436248289312;
          
          double Pval = A1;
          Pval += B1*cos(1.0*frq*time);
          Pval += C1*cos(2.0*frq*time);
          Pval += D1*cos(3.0*frq*time);
          n_k->P = Pval;
        } else if (sim == 3) {
	  double frq = 0.00174534439987236;
          double A1 = 7.79828e+06;
          double B1 = 428934;
          double B2 = -68367.4;
          double C1 = -1846.93;
          double C2 =  16060.2;
          double Pval = A1;
          Pval += B1*sin(1.0*frq*time) + B2*cos(1.0*frq*time);
          Pval += C1*sin(2.0*frq*time) + C2*cos(2.0*frq*time);
          n_k->P = Pval;
        }
      */
      }
    }


    for (int l = 0; l < n_k->adj_n; l++) {
      p_k = n_k->adj_p[l];
      if (p_k->left == n_k) {            // means left side of pipe p_k is connected to node j
#if 1       
	if (p_k->c_id != NULL) {
           sprintf(dmsg,"Left side is connected here\n");
	   debug_msg(dmsg);

	   if (j == 0) {
	      if (net->LFLAG==1) {
		n_k->F = ((p_k->c_id)->cratio)*n_k->P - sq2*(p_k->Wb_l);
        	//printf("Flux = %e\n",n_k->F/net->c);
	      }
	      else {}//n_k->F = net->F0;
	   } else n_k->F = ((p_k->c_id)->cratio)*n_k->P - sq2*(p_k->Wb_l);
           
           p_k->Pl = (p_k->c_id->cratio)*n_k->P;  // experimental 1
	   //p_k->Fl = (n_k->F)/net->c; old dumb
	   p_k->Fl = n_k->F;
	   //p_k->W_l = ovsq2*(((p_k->c_id)->cratio)*n_k->P + n_k->F);
	   p_k->W_l = ovsq2*(p_k->Pl + p_k->Fl);

	   sprintf(dmsg, "To pipe %p: flux is %.15e\tpressure is %.15e\tCompression = %.12e\n", p_k, (p_k->Fl), 0.000001*((p_k->c_id)->cratio)*n_k->P, (p_k->c_id)->cratio);
	   debug_msg(dmsg);
        } else {
	   if (j == 0) {
	      if (net->LFLAG == 1) {
		 n_k->F = n_k->P - sq2*(p_k->Wb_l);
	      } else {
		 n_k->F = net->F0;
		 //Beta = 0.5*(net->diss)/(p_k->d);
		 //n_k->F = p_k->f[1]/(1 + 0.5*Beta*dt*p_k->f[1]/p_k->p[1]) + (n_k->P - p_k->p[1]) - 0.5*dt*(p_k->q[1]+n_k->Q);
	      }
	   } else {
		n_k->F = n_k->P - sq2*(p_k->Wb_l);
           }
	   p_k->Pl = n_k->P;  // experimental 2
	   p_k->Fl = (n_k->F); //net->c;
           p_k->W_l = ovsq2*(p_k->Pl + p_k->Fl);
	   sprintf(dmsg, "To pipe %p: flux is %.15e\tpressure is %.15e\n", p_k, (p_k->Fl), 0.000001*n_k->P);
	   debug_msg(dmsg);
	}
#endif
      } else if ( p_k->right == n_k ) {
	n_k->F = sq2*(p_k->W_r) - n_k->P;
	p_k->Pr = n_k->P;  // experimental 3
	//p_k->Fr = (n_k->F)/net->c; // old dumb
	p_k->Fr = (n_k->F);
	p_k->Wb_r = ovsq2*(p_k->Pr - p_k->Fr);
        sprintf(dmsg, "To pipe %p: flux is %.15e\tpressure is %.15e\n", p_k, (p_k->Fr), 0.000001*n_k->P);
	debug_msg(dmsg);
      } else err_msg("Error in network construction");
    }
    //printf("Node %02d Complete\n", j);   
  }
}
Пример #30
0
int main(int argc, char *argv[])
{
    struct mbus	*m;
    char		 c_addr[60], *token_u[2], *token_e[2];
    int		 seed = (gethostid() << 8) | (getpid() & 0xff), final_iters;
    struct timeval	 timeout;
    int		 i, num_sessions = 0;
    char **xargv = xmalloc(argc);
    int  xargc=0;

#ifdef WIN32
    win32_create_null_window(); /* Needed to listen to messages */
#else
    signal(SIGCONT, sigchld_handler);
    signal(SIGCHLD, sigchld_handler);
    signal(SIGINT, sigint_handler);
    signal(SIGTERM, sigint_handler);
    signal(SIGHUP, sigint_handler);
#endif

    debug_msg("rat-%s started argc=%d\n", RAT_VERSION, argc);

    /* We have two modes: one for operation as a transcoder, one */
    /* when working as a normal end-system audio tool. We choose */
    /* based on the first command line argument supplied.        */
    if ((argc > 2) && (strcmp(argv[1], "-T") == 0)) {
        num_sessions = 2;
    } else {
        num_sessions = 1;
    }

    if (parse_options_early(argc, (const char**)argv) == FALSE) {
        return FALSE;
    }

    srand48(seed);
    snprintf(c_addr, 60, "(media:audio module:control app:rat id:%lu)", (unsigned long) getpid());
    debug_msg("c_addr = %s\n", c_addr);
    m = mbus_init(mbus_control_rx, mbus_err_handler, c_addr);
    if (m == NULL) {
        fatal_error("RAT v" RAT_VERSION, "Could not initialize Mbus: Is multicast enabled?");
        return FALSE;
    }

    /* pull out -X arguments */
    for(i=0; i<argc; i++) {
        if( strcmp(argv[i],"-X") == 0 ) {
            xargv[xargc] = argv[i];
            xargc++;
            i++;
            xargv[xargc] = argv[i];
            xargc++;
        }
    }


    if (ui_enabled) {
        token_u[0] = generate_token();
        fork_process(UI_NAME, c_addr, &pid_ui, 1, token_u, xargc, xargv);
        debug_msg("Controller waiting for %s from UI...\n", token_u[0]);
        if ((u_addr = mbus_rendezvous_waiting(m, "()", token_u[0], m, 20000000)) == NULL) {
            fatal_error("RAT v" RAT_VERSION, "MBUS Failed to rendezvous with UI - Likely firewall/VPN issue");
            return FALSE;
        }
        debug_msg("Controller has rendezvous'd with UI (%s)\n",u_addr);
    }

    token_e[0] = generate_token();
    token_e[1] = generate_token();
    fork_process(ENGINE_NAME, c_addr, &pid_engine, num_sessions, token_e, xargc, xargv);
    should_exit = FALSE;
    for (i = 0; i < num_sessions; i++) {
        debug_msg("Controller waiting for %s from media engine...\n", token_e[i]);
        if ((e_addr[i] = mbus_rendezvous_waiting(m, "()", token_e[i], m, 20000000)) == NULL ) {
            fatal_error("RAT v" RAT_VERSION, "Failed to rendezvous with media engine - Likely firewall/VPN issue");
            return FALSE;
        }
        debug_msg("Controller rendezvous'd with media engine (%s)\n",e_addr[i]);
    }

    if (parse_addresses(m, e_addr, argc, argv) == TRUE) {
        char	*peer;

        if (ui_enabled) {
            if ((peer = mbus_rendezvous_go(m, token_u[0], (void *) m, 20000000)) == NULL) {
                fatal_error("RAT v" RAT_VERSION, "Failed to rendezvous with UI - Likely firewall/VPN issue");
                return FALSE;
            }
            debug_msg("User interface is %s\n", peer);
        }
        for (i = 0; i < num_sessions; i++) {
            if ((peer = mbus_rendezvous_go(m, token_e[i], (void *) m, 20000000)) == NULL) {
                fatal_error("RAT v" RAT_VERSION, "Failed to rendezvous with UI - Likely firewall/VPN issue");
                return FALSE;
            }
            debug_msg("Media engine %d is %s\n", i, peer);
        }
        debug_msg("Parsing options\n");
        for (i = 0; i < num_sessions; i++) {
            parse_options_late(m, e_addr[i], argc, argv);
        }
        debug_msg("Entering main loop\n");
        final_iters = 25;
        while (final_iters > 0) {
            mbus_send(m);
            mbus_heartbeat(m, 1);
            mbus_retransmit(m);
            timeout.tv_sec  = 0;
            timeout.tv_usec = 20000;
#ifdef WIN32
            win32_check_children_running();
            win32_process_messages();
#endif
            mbus_recv(m, NULL, &timeout);
            if (should_exit) {
                final_iters--;
            }
        }
        if (ui_enabled) {
            terminate(m, u_addr, &pid_ui);
        }
        for (i = 0; i < num_sessions; i++) {
            terminate(m, e_addr[i], &pid_engine);
        }
    }

    if (ui_enabled) {
        kill_process(pid_ui);
    }
    kill_process(pid_engine);

#ifdef WIN32
    WSACleanup();
#endif
    if (ui_enabled) xfree(token_u[0]);
    xfree(token_e[0]);
    xfree(token_e[1]);
    xfree(xargv);
    debug_msg("Controller exit\n");
    return 0;
}