/** * \brief Constructor. * * Constructs a CQMemManager object with optionally defaulted values. * If no paramemters are set, it will default to no memory (0 bytes) * allocated and a 256 byte segregation length. If the requested * memory and segregation legnth are not 0 , it will allocate and * segregate the block * * \param [in] N Total memory (in bytes) to be allocated * \param [in] BlockSize Segregation block size * */ CQMemManager(size_t N = 0, size_t BlockSize = 2048) : mem_backend(), N_(N), BlockSize_(BlockSize), isAllocated_(false), NAlloc_(0) { if( N_ and BlockSize_ ) allocMem(); };
/* read and/or refresh the address book */ bool loadAddressBook(void) { char *buf, *bufend, *v, *last, *s, *t; bool cmt = false; char state = 0, c; int j, buflen, ln = 1; time_t mtime; if (!addressFile || (mtime = fileTimeByName(addressFile)) == -1 || mtime <= adbooktime) return true; debugPrint(3, "loading address book"); nzFree(addressList); addressList = 0; nads = 0; if (!fileIntoMemory(addressFile, &buf, &buflen)) return false; bufend = buf + buflen; for (s = t = last = buf; s < bufend; ++s) { c = *s; if (cmt) { if (c != '\n') continue; cmt = false; } if (c == ':') { /* delimiter */ if (state == 0) { setError(MSG_ABNoAlias, ln); freefail: nzFree(buf); nads = 0; return false; } while (t[-1] == ' ' || t[-1] == '\t') --t; if (state == 1) { *t++ = c; state = 2; continue; } c = '#'; /* extra fields are ignored */ } /* : */ if (c == '#') { cmt = true; continue; } if (c == '\n') { ++ln; if (state == 0) continue; if (state == 1) { setError(MSG_ABNoColon, ln - 1); goto freefail; } if (state == 3) { ++nads; while (isspaceByte(t[-1])) --t; *t = 0; v = strchr(last, ':'); if (v - last >= 16) { setError(MSG_ABAliasLong, ln - 1); goto freefail; } ++v; if (t - v >= 64) { setError(MSG_ABMailLong, ln - 1); goto freefail; } if (!strchr(v, '@')) { setError(MSG_ABNoAt, ln - 1); goto freefail; } if (strpbrk(v, " \t")) { setError(MSG_ABMailSpaces, ln - 1); goto freefail; } while (last < t) { if (!isprintByte(*last)) { setError(MSG_AbMailUnprintable, ln - 1); goto freefail; } ++last; } *t++ = c; } else t = last; /* back it up */ last = t; state = 0; continue; } /* nl */ if ((c == ' ' || c == '\t') && (state == 0 || state == 2)) continue; if (state == 0) state = 1; if (state == 2) state = 3; *t++ = c; } *t = 0; if (state) { setError(MSG_ABUnterminated); goto freefail; } if (nads) { addressList = allocMem(nads * sizeof(struct ALIAS)); j = 0; for (s = buf; *s; s = t + 1, ++j) { t = strchr(s, ':'); memcpy(addressList[j].name, s, t - s); addressList[j].name[t - s] = 0; s = t + 1; t = strchr(s, '\n'); memcpy(addressList[j].email, s, t - s); addressList[j].email[t - s] = 0; } } /* aliases are present */ nzFree(buf); adbooktime = mtime; return true; } /* loadAddressBook */
static struct OBarjut * _inst( const iONode ini, const iOTrace trc ) { iOBarjut __Barjut = allocMem( sizeof ( struct OBarjut ) ); iOBarjutData data = allocMem( sizeof ( struct OBarjutData ) ); /* Initialize data->xxx members... */ iOAttr attr = NULL; const char *flow = "none"; const char *parity = "none"; int timeout = 50; data->serialOK = False; data->initOK = False; MemOp.basecpy( __Barjut, &BarjutOp, 0, sizeof ( struct OBarjut ), data ); TraceOp.set( trc ); // data->mux = MutexOp.inst( StrOp.fmt( "serialMux%08X", data ), True ); // data->fbstate = allocMem( 31 * 16 * sizeof ( struct FBState ) ); /* Evaluate attributes. */ data->device = StrOp.dup( wDigInt.getdevice( ini ) ); data->iid = StrOp.dup( wDigInt.getiid( ini ) ); data->bps = 115200; // data->bits = 8; // data->stopBits = 1; // data->timeout = wDigInt.gettimeout( ini ); // data->timeout = 50; // data->parity = none; // data->flow = noflow; // data->ctsretry = wDigInt.getctsretry( ini ); // data->ctsretry = 0; data->timeout = wDigInt.gettimeout( ini ); // f�r die Pollingrate der Module if( data->timeout <= 0 ) { data->timeout = 1; } TraceOp.trc( name, TRCLEVEL_INFO, __LINE__, 9999, "----------------------------------------" ); TraceOp.trc( name, TRCLEVEL_INFO, __LINE__, 9999, "BarJuT %d.%d.%d", vmajor, vminor, patch ); TraceOp.trc( name, TRCLEVEL_INFO, __LINE__, 9999, "----------------------------------------" ); TraceOp.trc( name, TRCLEVEL_INFO, __LINE__, 9999, "BarJuT[%s]: %s,%d,%s,%d,%d,%s,%d", wDigInt.getiid( ini ) != NULL ? wDigInt.getiid( ini ) : "", data->device, data->bps, parity, 8, 1, flow, timeout ); data->serial = SerialOp.inst( data->device ); SerialOp.setFlow( data->serial, -1 ); SerialOp.setLine( data->serial, data->bps, 8, 1, none, wDigInt.isrtsdisabled( ini ) ); SerialOp.setTimeout( data->serial, timeout, timeout ); data->serialOK = SerialOp.open( data->serial ); if( data->serialOK ) { data->run = True; data->runFinished = False; SystemOp.inst( ); data->reader = ThreadOp.inst( "Barjutfb", &__BarjutReader, __Barjut ); ThreadOp.start( data->reader ); } else TraceOp.trc( name, TRCLEVEL_EXCEPTION, __LINE__, 9999, "Could not init BarJuT port!" ); instCnt++; return __Barjut; }
static void retsFromOdbc(void) { void *q, *q1; int i, l; int fd, flags; bool yearfirst, indata = false; long dt; /* temporarily hold date or time */ char *s; short c_type; /* C data type */ long input_length, output_length; char tbuf[20]; /* temp buf, for dates and times */ double fmoney; /* float version of money */ int blobcount = 0; bool fbc = fetchBlobColumns; /* no blobs unless proven otherwise */ rv_blobLoc = 0; rv_blobSize = nullint; if(!rv_numRets) errorPrint("@calling retsFromOdbc() with no returns pending"); stmt_text = "retsFromOdbc"; debugStatement(); /* count the blobs */ if(fbc) for(i = 0; i < rv_numRets; ++i) if(rv_type[i] == 'B' || rv_type[i] == 'T') ++blobcount; if(blobcount > 1) { i_puts(MSG_DBManyBlobs); fbc = false; } for(i = 0; i < rv_numRets; ++i) { if(!indata) { q = va_arg(sqlargs, void *); if(!q) { if(i) break; indata = true; } } if(indata) { if(rv_type[i] == 'S') { q = retstring[i]; rv_data[i].ptr = q; } else q = rv_data + i; } if((int)q < 1000 && (int)q > -1000) errorPrint("2retsFromOdbc, pointer too close to 0"); q1 = q; tbuf[0] = 0; output_length = 0; switch (rv_type[i]) { case 'S': c_type = SQL_C_CHAR; input_length = STRINGLEN + 1; *(char *)q = 0; /* null */ break; case 'C': c_type = SQL_C_CHAR; input_length = 2; *(char *)q = 0; /* null */ q1 = tbuf; break; case 'F': c_type = SQL_C_DOUBLE; input_length = 8; *(double *)q = nullfloat; /* null */ break; case 'N': c_type = SQL_C_SLONG; input_length = 4; *(long *)q = nullint; /* null */ break; case 'M': c_type = SQL_C_DOUBLE; input_length = 8; fmoney = nullfloat; q1 = &fmoney; break; case 'D': c_type = SQL_C_CHAR; input_length = 11; q1 = tbuf; break; case 'I': c_type = SQL_C_CHAR; input_length = 10; q1 = tbuf; break; case 'B': case 'T': c_type = SQL_C_BINARY; input_length = sizeof (blobbuf); q1 = blobbuf; *(long *)q = nullint; break; default: errorPrint("@retsFromOdbc, rv_type[%d] = %c", i, rv_type[i]); } /* switch */ if(everything_null || c_type == SQL_C_BINARY && !fbc) { rc = SQL_SUCCESS; output_length = SQL_NULL_DATA; } else { rc = SQLGetData(hstmt, (ushort) (i + 1), c_type, q1, input_length, &output_length); /* we'll deal with blob overflow later */ if(rc == SQL_SUCCESS_WITH_INFO && c_type == SQL_C_BINARY && output_length > sizeof (blobbuf)) rc = SQL_SUCCESS; if(errorTrap(0)) break; if(output_length == SQL_NO_TOTAL) errorPrint ("@retsFromOdbc cannot get size of data for column %d", i + 1); } /* Postprocess the return values. */ /* For instance, turn string dates into our own 4-byte format. */ s = tbuf; clipString(s); switch (rv_type[i]) { case 'C': *(char *)q = tbuf[0]; break; case 'S': clipString(q); break; case 'D': yearfirst = false; if(s[4] == '-') yearfirst = true; dt = stringDate(s, yearfirst); if(dt < 0) errorPrint("@database holds invalid date %s", s); *(long *)q = dt; break; case 'I': /* thanks to stringTime(), this works for either hh:mm or hh:mm:ss */ if(s[0] == 0) *(long *)q = nullint; else { /* Note that Informix introduces a leading space, how about ODBC? */ leftClipString(s); if(s[1] == ':') shiftRight(s, '0'); dt = stringTime(s); if(dt < 0) errorPrint("@database holds invalid time %s", s); *(long *)q = dt; } break; case 'M': if(fmoney == nullfloat) dt = nullint; else dt = fmoney * 100.0 + 0.5; *(long *)q = dt; break; case 'B': case 'T': if(output_length == SQL_NULL_DATA) break; /* note, 0 length blob is treated as a null blob */ if(output_length == 0) break; /* the size of the blob is returned, in an int. */ *(long *)q = output_length; rv_blobSize = output_length; if(isnullstring(rv_blobFile)) { /* the blob is always allocated; you have to free it! */ /* SQL doesn't null terminate its text blobs, but we do. */ rv_blobLoc = allocMem(output_length + 1); l = output_length; if(l > sizeof (blobbuf)) l = sizeof (blobbuf); memcpy(rv_blobLoc, blobbuf, l); if(l < output_length) { /* more to do */ long waste; rc = SQLGetData(hstmt, (ushort) (i + 1), c_type, (char *)rv_blobLoc + l, output_length - l, &waste); if(rc) { nzFree(rv_blobLoc); rv_blobLoc = 0; *(long *)q = nullint; errorTrap(0); goto breakloop; } /* error getting rest of blob */ } /* blob is larger than the buffer */ if(rv_type[i] == 'T') /* null terminate */ ((char *)rv_blobLoc)[output_length] = 0; break; } /* blob in memory */ /* at this point the blob is being dumped into a file */ flags = O_WRONLY | O_BINARY | O_CREAT | O_TRUNC; if(rv_blobAppend) flags = O_WRONLY | O_BINARY | O_CREAT | O_APPEND; fd = eopen(rv_blobFile, flags, 0666); rc = SQL_SUCCESS; while(true) { int outbytes; l = output_length; if(l > sizeof (blobbuf)) l = sizeof (blobbuf); outbytes = write(fd, blobbuf, l); if(outbytes < l) { close(fd); errorPrint("2cannot write to file %s, errno %d", rv_blobFile, errno); } if(l == output_length) break; /* get the next chunk from ODBC */ rc = SQLGetData(hstmt, (ushort) (i + 1), c_type, q1, input_length, &output_length); if(rc == SQL_SUCCESS_WITH_INFO && output_length > input_length) rc = SQL_SUCCESS; /* data truncation error */ } close(fd); errorTrap(0); break; } /* switch */ } /* loop over returned elements */
static iOSlot __getSlot(iOMttmFccData data, iONode node) { int steps = wLoc.getspcnt(node); int addr = wLoc.getaddr(node); int fncnt = wLoc.getfncnt(node); Boolean ebreak = True; Boolean sx1 = False; byte index = 0xFF; iOSlot slot = NULL; byte cmd[32] = {0x79, 0x01}; slot = (iOSlot)MapOp.get( data->lcmap, wLoc.getid(node) ); if( slot != NULL ) { TraceOp.trc( name, TRCLEVEL_DEBUG, __LINE__, 9999, "slot exist for %s", wLoc.getid(node) ); return slot; } if( StrOp.equals( wLoc.prot_S, wLoc.getprot(node) ) ) { steps = 31; sx1 = True; ebreak = False; TraceOp.trc( name, TRCLEVEL_MONITOR, __LINE__, 9999, "sx1, steps=%d, fncnt=%d", steps, fncnt ); } /* Die DCC-Lok mit der langen Adresse 1234 und 126 Fahrstufen soll an die FCC- Digitalzentrale angemeldet werden: Bestimmung: 1234 (binär: 00010011010010) DCC-Lokadresse: 00010011010010 00 entspricht 0x1348 Es ist daher Folgendes an die FCC-Digitalzentrale zu senden: Vom PC: 0x79 0x01 0x13 0x48 0x07 */ else if( StrOp.equals( wLoc.prot_N, wLoc.getprot(node) ) ) { /* short DCC */ addr = addr << 2; cmd[4] = steps > 100 ? 0x05:(steps > 14 ? 0x81:0x91); steps = steps > 100 ? 126:(steps > 14 ? 28:14); TraceOp.trc( name, TRCLEVEL_MONITOR, __LINE__, 9999, "short DCC, steps=%d, fncnt=%d", steps, fncnt ); } else if( StrOp.equals( wLoc.prot_L, wLoc.getprot(node) ) ) { /* long DCC */ addr = addr << 2; cmd[4] = steps > 100 ? 0x07:(steps > 14 ? 0x83:0x93); steps = steps > 100 ? 126:(steps > 14 ? 28:14); TraceOp.trc( name, TRCLEVEL_MONITOR, __LINE__, 9999, "long DCC, steps=%d, fncnt=%d", steps, fncnt ); } else if( StrOp.equals( wLoc.prot_M, wLoc.getprot(node) ) ) { /* MM */ /* Die MM-Lok mit der Adresse 218 soll an die FCC-Digitalzentrale angemeldet werden: Bestimmung: 218 (binär: 00000011011010) MM-Lokadresse: 00000011011010 00 entspricht 0x0368 Es ist daher Folgendes an die FCC-Digitalzentrale zu senden: Vom PC: 0x79 0x01 0x03 0x68 0x02 */ addr = addr << 2; cmd[4] = fncnt == 4 ? 0x82:0x92; steps = 14; TraceOp.trc( name, TRCLEVEL_MONITOR, __LINE__, 9999, "MM, steps=%d, fncnt=%d", steps, fncnt ); } else { /* Die SX2-Lok mit der Adresse 5678 soll an die FCC-Digitalzentrale angemeldet werden: Rechnung: 5678 / 100 = 56 (binär: 0111000) Rest 78 (binär: 1001110) SX2-Lokadresse: 0111000 1001110 00 entspricht 0x7138 Es ist daher Folgendes an die FCC-Digitalzentrale zu senden: Vom PC: 0x79 0x01 0x71 0x38 0x04 */ addr = (wLoc.getaddr(node) / 100) << 9; addr = addr + ((wLoc.getaddr(node) % 100) << 2); /* default SX2 */ cmd[4] = 0x04; steps = 127; ebreak = False; TraceOp.trc( name, TRCLEVEL_MONITOR, __LINE__, 9999, "default SX2, steps=%d, fncnt=%d", steps, fncnt ); } cmd[2] = addr / 256; cmd[3] = addr % 256; if( sx1 || __transact( data, cmd, 5, &index, 1 ) ) { TraceOp.trc( name, TRCLEVEL_MONITOR, __LINE__, 9999, "got index %d for %s", index, wLoc.getid(node) ); slot = allocMem( sizeof( struct slot) ); slot->addr = addr; slot->index = index; slot->protocol = cmd[4]; slot->steps = steps; slot->ebreak = ebreak; slot->sx1 = sx1; if (sx1) { slot->sx1aux1 = slot->sx1aux2 = 0; if (fncnt > 0) { slot->sx1aux1 = addr+1; /* First SX1 auxchannel at loco address + 1 */ TraceOp.trc( name, TRCLEVEL_MONITOR, __LINE__, 9999, "SX1 Auxchannel 1 Addr=%d", slot->sx1aux1 ); } if (fncnt > 8) { slot->sx1aux2 = addr+2; /* Second SX1 auxchannel at loco address + 2 */ TraceOp.trc( name, TRCLEVEL_MONITOR, __LINE__, 9999, "SX1 Auxchannel 2 Addr=%d", slot->sx1aux2 ); } } slot->bus = wLoc.getbus(node); slot->id = StrOp.dup(wLoc.getid(node)); if( MutexOp.wait( data->lcmux ) ) { MapOp.put( data->lcmap, wLoc.getid(node), (obj)slot); MutexOp.post(data->lcmux); } TraceOp.trc( name, TRCLEVEL_INFO, __LINE__, 9999, "slot created for %s", wLoc.getid(node) ); } return slot; }
int main (int argc, char **argv){ int errnum; // alokovani pameti errnum = allocMem(); if (errnum != EOK) { fprintf(stderr, "%s", ecode[errnum]); return 2; } // overeni parametru errnum = getParameters(argc, argv); if (errnum != EOK) { fprintf(stderr, "%s", ecode[errnum]); return 1; } //generovani nahodnych cisel srand(time(NULL)); semafors->waiting = sem_open("/bayer05_waiting", O_CREAT, S_IRUSR|S_IWUSR, 1); semafors->boarding_Serf = sem_open("/bayer05_boarding_Serf", O_CREAT, S_IRUSR|S_IWUSR, 0); semafors->boarding_Hacker = sem_open("/bayer05_boarding_Hacker", O_CREAT, S_IRUSR|S_IWUSR, 0); semafors->member = sem_open("/bayer05_member", O_CREAT, S_IRUSR|S_IWUSR, 0); semafors->landing = sem_open("/bayer05_landing", O_CREAT, S_IRUSR|S_IWUSR, 0); semafors->finish = sem_open("/bayer05_finish", O_CREAT, S_IRUSR|S_IWUSR, 0); semafors->boating = sem_open("/bayer05_boating", O_CREAT, S_IRUSR|S_IWUSR, 0); semafors->checkready = sem_open("/bayer05_checkready", O_CREAT, S_IRUSR|S_IWUSR, 1); // overeni korektnosti vytvareni semaforu if(semafors->waiting == SEM_FAILED || semafors->boarding_Serf == SEM_FAILED || semafors->boarding_Hacker == SEM_FAILED || semafors->member == SEM_FAILED || semafors->landing == SEM_FAILED || semafors->finish == SEM_FAILED || semafors->boating == SEM_FAILED || semafors->checkready == SEM_FAILED) { fprintf(stderr, "%s", ecode[ESEMAPHORE]); errnum = clearSources(); if (errnum != EOK) { fprintf(stderr, "%s", ecode[errnum]); return 2; } return 2; } fileopen(); semafors->pocet = 1; semafors->molo_Hackers = 0; semafors->molo_Serfs = 0; semafors->dec = 4; semafors->end = 0; pid_t pid, pid2, pid3; pid = fork(); if (pid == 0) { for ( int i = 0 ; i < semafors->members; i++) { if (semafors->serfSleep != 0) { usleep(rand()%(semafors->serfSleep)*1000); } pid2 = fork(); if (pid2 == 0) { SerfProc(i+1); exit(0); } else if (pid2 < 0) { errorpid(pid2); } } for ( int i = 0 ; i < semafors->members; i++) { wait(NULL); } exit(0); } else if (pid < 0) { errorpid(pid); } else { pid = fork(); if(pid == 0) { for( int i = 0 ; i < semafors->members; i++) { if (semafors->hackerSleep != 0) { usleep(rand()%(semafors->hackerSleep)*1000); } pid3 = fork(); if (pid3 == 0) { HackerProc(i+1); exit(0); } else if (pid3 < 0) { errorpid(pid3); } } for ( int i = 0 ; i < semafors->members; i++) { wait(NULL); } exit(0); } else if (pid < 0) { errorpid(pid); } else { signal(SIGTERM, killProces); signal(SIGINT, killProces); wait(NULL); wait(NULL); // exit(0); } } errnum = clearSources(); if (errnum != EOK) { fprintf(stderr, "%s", ecode[errnum]); return 2; } return 0; }
static iONode __translate( iOZimoCAN inst, iONode node ) { iOZimoCANData data = Data(inst); iONode rsp = NULL; TraceOp.trc( name, TRCLEVEL_MONITOR, __LINE__, 9999, "translate: %s:%s", NodeOp.getName( node ), NodeOp.getStr(node, "cmd", "-") ); if( StrOp.equals( NodeOp.getName( node ), wFbInfo.name() ) ) { } /* System command. Mode 1, EIN: Normaler Fahrbetrieb Mode 2, SSP0: Sammelstopp FS0, eigentlich 'Broadcast Fahrstufe 0' Mode 3, SSPE: Emergency Sammelstopp, eigentlich 'Broadcast E-Stopp' Mode 4, OFF: Schlichtweg 'Schiene AUS' */ else if( StrOp.equals( NodeOp.getName( node ), wSysCmd.name() ) ) { const char* cmdstr = wSysCmd.getcmd( node ); if( StrOp.equals( cmdstr, wSysCmd.stop ) ) { /* CS off */ byte* msg = allocMem(32); msg[0] = __makePacket(msg+1, SYSTEM_CONTROL_GROUP, SYSTEM_POWER, MODE_CMD, 4, data->NID, data->masterNID, SYSTEM_POWER_TRACK_ALL, Zs100_PortStateCmd_OFF, 0, 0, 0, 0); TraceOp.trc( name, TRCLEVEL_MONITOR, __LINE__, 9999, "request power OFF" ); ThreadOp.post(data->writer, (obj)msg); data->power = False; __reportState(inst, False); } else if( StrOp.equals( cmdstr, wSysCmd.go ) ) { /* CS on */ byte* msg = allocMem(32); msg[0] = __makePacket(msg+1, SYSTEM_CONTROL_GROUP, SYSTEM_POWER, MODE_CMD, 4, data->NID, data->masterNID, SYSTEM_POWER_TRACK_ALL, Zs100_PortStateCmd_Run, 0, 0, 0, 0); TraceOp.trc( name, TRCLEVEL_MONITOR, __LINE__, 9999, "request power ON (RUN)" ); ThreadOp.post(data->writer, (obj)msg); data->power = True; __reportState(inst, False); } else if( StrOp.equals( cmdstr, wSysCmd.ebreak ) ) { /* CS ebreak */ byte* msg = allocMem(32); if( wDigInt.isv0onebreak(data->ini) ) { msg[0] = __makePacket(msg+1, SYSTEM_CONTROL_GROUP, SYSTEM_POWER, MODE_CMD, 4, data->NID, data->masterNID, SYSTEM_POWER_TRACK_ALL, Zs100_PortStateCmd_SSP0, 0, 0, 0, 0); TraceOp.trc( name, TRCLEVEL_MONITOR, __LINE__, 9999, "V 0 on ebreak (SSP0)" ); } else { msg[0] = __makePacket(msg+1, SYSTEM_CONTROL_GROUP, SYSTEM_POWER, MODE_CMD, 4, data->NID, data->masterNID, SYSTEM_POWER_TRACK_ALL, Zs100_PortStateCmd_SSPE, 0, 0, 0, 0); TraceOp.trc( name, TRCLEVEL_MONITOR, __LINE__, 9999, "emergency break (SSPE)" ); data->power = False; __reportState(inst, False); } ThreadOp.post(data->writer, (obj)msg); } } /* Loco command. */ else if( StrOp.equals( NodeOp.getName( node ), wLoc.name() ) ) { iOSlot slot = __getSlot( inst, node ); if( slot != NULL ) { if( StrOp.equals( wLoc.shortid, wLoc.getcmd(node) ) ) { byte* msg = allocMem(256); msg[0] = __makeStringPacket( msg+1, DATA_GROUP, DATA_NAME, MODE_CMD, data->NID, slot->nid, 0, 0, slot->id ); TraceOp.trc( name, TRCLEVEL_MONITOR, __LINE__, 9999, "set ID for loco %s with NID=0x%X", slot->id, slot->nid ); ThreadOp.post(data->writer, (obj)msg); } else if( StrOp.equals( wLoc.shuntingon, wLoc.getcmd(node) ) ) { slot->shunting = True; TraceOp.trc( name, TRCLEVEL_MONITOR, __LINE__, 9999, "set shunting for loco %s to %s", slot->id, slot->shunting?"ON":"OFF" ); } else if( StrOp.equals( wLoc.shuntingoff, wLoc.getcmd(node) ) ) { slot->shunting = False; TraceOp.trc( name, TRCLEVEL_MONITOR, __LINE__, 9999, "set shunting for loco %s to %s", slot->id, slot->shunting?"ON":"OFF" ); } else if( StrOp.equals( wLoc.manualon, wLoc.getcmd(node) ) ) { slot->manual = True; TraceOp.trc( name, TRCLEVEL_MONITOR, __LINE__, 9999, "set manual for loco %s to %s", slot->id, slot->manual?"ON":"OFF" ); } else if( StrOp.equals( wLoc.manualoff, wLoc.getcmd(node) ) ) { slot->manual = False; TraceOp.trc( name, TRCLEVEL_MONITOR, __LINE__, 9999, "set manual for loco %s to %s", slot->id, slot->manual?"ON":"OFF" ); } else { byte* msg = allocMem(32); int Div = 1; /* Speed divider */ int V = 0; Boolean dir = wLoc.isdir(node); if( wLoc.getV( node ) != -1 ) { if( StrOp.equals( wLoc.getV_mode( node ), wLoc.V_mode_percent ) ) V = (wLoc.getV( node ) * 1023) / 100; else if( wLoc.getV_max( node ) > 0 ) V = (wLoc.getV( node ) * 1023) / wLoc.getV_max( node ); } if( slot->shunting ) { V |= 0x2000; // Shunting mode } if( slot->manual ) { V |= 0x4000; // Manual mode } msg[0] = __makePacket(msg+1, MOBILE_CONTROL_GROUP, MOBILE_SPEED, MODE_CMD, 6, data->NID, slot->nid, (V&0xFF), (V>>8) | (dir?0x00:0x04), Div, 0, 0, 0); TraceOp.trc( name, TRCLEVEL_MONITOR, __LINE__, 9999, "Set loco speed to %d, dir=%s div=%d flags=%X for %s", V & 0x03FF, dir?"fwd":"rev", Div, V & 0xFC00, slot->id ); ThreadOp.post(data->writer, (obj)msg); } } }
/* This thread is only writing the results to stdout */ void * writerThread() { void * buf = allocMem( blockSize100k * 101000 + 600 ); size_t blockSize; bz_stream * strm; bz_stream_state_out savedState; int wasStateSaved = 0; concurritFuncEnter(writerThread, 0, 0); pthread_mutex_lock( &outChunksMutex ); for( ; !done ; ) { if ( outChunksTail == -1 || ! outChunks[ outChunksTail ] ) { if(done) { pthread_mutex_unlock( &outChunksMutex ); break; } concurritAtPc(46); pthread_cond_wait( &outChunksFlushCondition, &outChunksMutex ); if(done) { pthread_mutex_unlock( &outChunksMutex ); break; } } pthread_mutex_unlock( &outChunksMutex ); printf("flushing outchunk %d\n", outChunksTail ); strm = outChunks[ outChunksTail ]; if ( wasStateSaved ) BZ2_bzCompressRestoreOutputState( strm, &savedState ); blockSize = BZ2_bzCompressStoreBlocksort( strm, buf, strm->avail_in ); BZ2_bzCompressSaveOutputState( strm, &savedState ); wasStateSaved = 1; BZ2_bzCompressEnd( strm ); #ifdef NICKEDIT if ( blockSize && fwrite( buf, blockSize, 1, nullout) != 1 ) { printf("Error writing to nullout\n" ); exit( 1 ); } #else if ( blockSize && fwrite( buf, blockSize, 1, stdout ) != 1 ) { printf("Error writing to stdout\n" ); exit( 1 ); } #endif free( strm ); outChunks[ outChunksTail ] = NULL; /* Since we have output the tail chunk, increase the tail, notifying a thread in case it is waiting for a free chunk.*/ pthread_mutex_lock( &outChunksMutex ); ++outChunksTail; if ( outChunksTail == outChunksCount ) outChunksTail = 0; pthread_cond_signal( &outChunksAvailableCondition ); /* If we empty the ring buffer out, mark it as empty */ if ( outChunksTail == outChunksHead ) outChunksTail = -1; concurritAtPc(47); } concurritFuncReturn(writerThread, 0); }
/* Read the entire message from js, then take action. * Thus messages will remain in sync. */ static int readMessage(void) { int l; char *msg; /* error message from js */ if (readFromJS(&head, sizeof(head)) < 0) return -1; /* read failed */ if (head.magic != EJ_MAGIC) { /* this should never happen */ js_kill(); i_puts(MSG_JSEngineSync); markAllDead(); return -1; } if (head.highstat >= EJ_HIGH_HEAP_FAIL) { js_kill(); /* perhaps a helpful message, before we close down js sessions */ if (head.highstat == EJ_HIGH_PROC_FAIL) allowJS = false; if (head.lowstat == EJ_LOW_EXEC) i_puts(MSG_JSEngineExec); if (head.lowstat == EJ_LOW_MEMORY) i_puts(MSG_JavaMemError); if (head.lowstat == EJ_LOW_RUNTIME) i_puts(MSG_JSEngineRun); if (head.lowstat == EJ_LOW_SYNC) i_puts(MSG_JSEngineSync); markAllDead(); return -1; } if (head.side) { effects = allocMem(head.side + 1); if (readFromJS(effects, head.side) < 0) { free(effects); effects = 0; return -1; } effects[head.side] = 0; // because debugPrint always puts on a newline effects[head.side - 1] = 0; debugPrint(4, "< side effects\n%s", effects); processEffects(); } /* next grab the error message, if there is one */ l = head.msglen; if (l) { msg = allocMem(l + 1); if (readFromJS(msg, l)) { free(msg); return -1; } msg[l] = 0; if (debugLevel >= 3) { /* print message, this will be in English, and mostly for our debugging */ if (jsSourceFile) { if (debugFile) fprintf(debugFile, "%s line %d: ", jsSourceFile, head.lineno); else printf("%s line %d: ", jsSourceFile, head.lineno); } debugPrint(3, "%s", msg); } free(msg); } /* Read in the requested property, if there is one. * The calling function must handle the property. */ l = head.proplength; proptype = head.proptype; if (l) { propval = allocMem(l + 1); if (readFromJS(propval, l)) { free(propval); propval = 0; return -1; } propval[l] = 0; } /* stop at the first js error when debugging */ if (head.msglen && debugLevel >= 5) { head.highstat = EJ_HIGH_CX_FAIL; head.lowstat = 0; debugPrint(5, "js abort due to error while debugging"); } if (head.highstat == EJ_HIGH_CX_FAIL) { if (head.lowstat == EJ_LOW_VARS) i_puts(MSG_JSEngineVars); if (head.lowstat == EJ_LOW_CX) i_puts(MSG_JavaContextError); if (head.lowstat == EJ_LOW_WIN) i_puts(MSG_JavaWindowError); if (head.lowstat == EJ_LOW_DOC) i_puts(MSG_JavaObjError); if (head.lowstat == EJ_LOW_CLOSE) i_puts(MSG_PageDone); else i_puts(MSG_JSSessionFail); freeJavaContext(cw); /* should I free and zero the property at this point? */ } return 0; } /* readMessage */
static iOSlot __getSlot(iOZimoCAN inst, iONode node) { iOZimoCANData data = Data(inst); int addr = wLoc.getaddr(node); iOSlot slot = NULL; byte* msg = NULL; byte M1 = 0; byte M2 = 0; slot = (iOSlot)MapOp.get( data->lcmap, wLoc.getid(node) ); if( slot != NULL ) { TraceOp.trc( name, TRCLEVEL_DEBUG, __LINE__, 9999, "slot exist for %s", wLoc.getid(node) ); return slot; } slot = allocMem( sizeof( struct slot) ); slot->addr = addr; slot->nid = addr; slot->id = StrOp.dup(wLoc.getid(node)); slot->lights = wLoc.isfn(node); slot->dir = wLoc.isdir(node); slot->steps = wLoc.getspcnt(node); slot->fncnt = wLoc.getfncnt(node); slot->shunting = False; if( StrOp.equals( wLoc.prot_M, wLoc.getprot( node ) ) ) { /* Motorola */ slot->prot = 2; slot->nid += 0x2800; } else if( StrOp.equals( wLoc.prot_F, wLoc.getprot( node ) ) ) { /* MFX */ slot->prot = 4; slot->nid += 0x8000; } else /* Default DCC */ slot->prot = 1; if( MutexOp.wait( data->lcmux ) ) { MapOp.put( data->lcmap, wLoc.getid(node), (obj)slot); MutexOp.post(data->lcmux); } msg = allocMem(32); msg[0] = __makePacket(msg+1, MOBILE_CONTROL_GROUP, MOBILE_STATE, MODE_REQ, 2, data->NID, slot->nid, 0, 0, 0, 0, 0, 0); TraceOp.trc( name, TRCLEVEL_MONITOR, __LINE__, 9999, "query state for loco %s with NID=0x%X", slot->id, slot->nid ); ThreadOp.post(data->writer, (obj)msg); msg = allocMem(32); M1 = slot->steps + (slot->prot << 4); M2 = slot->fncnt; msg[0] = __makePacket(msg+1, MOBILE_CONTROL_GROUP, MOBILE_MODE, MODE_CMD, 4, data->NID, slot->nid, M1, M2, 0, 0, 0, 0); TraceOp.trc( name, TRCLEVEL_MONITOR, __LINE__, 9999, "set mode parameters, M1=%d M2=%d, for loco %s", M1, M2, slot->id ); ThreadOp.post(data->writer, (obj)msg); msg = allocMem(256); msg[0] = __makeStringPacket( msg+1, DATA_GROUP, DATA_NAME, MODE_CMD, data->NID, slot->nid, 0, 0, slot->id ); TraceOp.trc( name, TRCLEVEL_MONITOR, __LINE__, 9999, "set name for loco %s with NID=0x%X", slot->id, slot->nid ); ThreadOp.post(data->writer, (obj)msg); TraceOp.trc( name, TRCLEVEL_INFO, __LINE__, 9999, "slot created for %s", wLoc.getid(node) ); return slot; }
static void processEffects(void) { char *s, *t, *v; char c; jsobjtype p; int n; struct inputChange *ic; if (!effects) return; s = effects; while (c = *s) { /* another effect */ s += 2; v = strstr(s, "`~@}"); /* end marker */ /* There should always be an end marker - * unless there is a spurious null in the string. */ if (!v) break; *v = 0; switch (c) { case 'w': /* document.write */ dwStart(); stringAndString(&cw->dw, &cw->dw_l, s); break; case 'n': /* new window */ /* url on one line, name of window on next line */ t = strchr(s, '\n'); *t = 0; javaOpensWindow(s, t + 1); break; case 'v': /* value = "foo" */ t = strchr(s, '='); *t++ = 0; sscanf(s, "%p", &p); prepareForField(t); javaSetsTagVar(p, t); break; case 't': /* js timer */ n = strtol(s, &t, 10); s = t + 1; t = strchr(s, '|'); *t++ = 0; v[-2] = 0; sscanf(t, "%p", &p); ic = allocMem(sizeof(struct inputChange) + strlen(s)); // Yeah I know, this isn't a pointer to htmlTag. ic->t = p; ic->tagno = n; ic->major = 't'; ic->minor = v[-1]; strcpy(ic->value, s); addToListBack(&inputChangesPending, ic); break; case 'c': /* cookie */ /* Javascript does some modest syntax checking on the cookie before * passing it back to us, so I'm just going to assume it works. */ receiveCookie(cw->fileName, s); break; case 'f': c = *s++; sscanf(s, "%p", &p); javaSubmitsForm(p, (c == 'r')); break; case 'i': c = *s++; /* h = inner html, t = inner text */ t = strchr(s, '|'); *t++ = 0; sscanf(s, "%p", &p); javaSetsInner(p, t, c); break; case 'l': c = *s; s += 2; sscanf(s, "%p", &p); s = strchr(s, ',') + 1; javaSetsLinkage(false, c, p, s); break; } /* switch */ /* skip past end marker + newline */ s = v + 5; } /* loop over effects */ free(effects); effects = 0; } /* processEffects */
static void _updateLoader( void* threadinst ) { iOThread th = (iOThread)threadinst; Softwareupdates* o = (Softwareupdates*)ThreadOp.getParm( th ); bool OK = true; if( o->m_ReleaseNode != NULL ) { iONode patch = wRelease.getpatch(o->m_ReleaseNode); while( patch!=NULL && OK ) { if(wPatch.isdownload(patch)) { TraceOp.trc( "updates", TRCLEVEL_INFO, __LINE__, 9999, "downloading [%s]...", wPatch.getfile(patch) ); iOSocket sh = SocketOp.inst( wGui.getupdatesserver(wxGetApp().getIni()), 80, False, False, False ); if( SocketOp.connect( sh ) ) { TraceOp.trc( "updates", TRCLEVEL_INFO, __LINE__, 9999, "Connected to rocrail.net" ); char* releasename = StrOp.dup(wGui.releasename); StrOp.replaceAll( releasename, ' ', '\0'); char* httpget = StrOp.fmt("GET /releases/%s/%s.%s.%s.%d HTTP/1.1\nHost: www.rocrail.net\n\n", StrOp.strlwr( releasename ), wPatch.getfile(patch), wPatch.getos(patch), wRelease.getversion(o->m_ReleaseNode), wPatch.getnr(patch)); TraceOp.trc( "updates", TRCLEVEL_INFO, __LINE__, 9999, "%s", httpget ); SocketOp.write( sh, httpget, StrOp.len(httpget) ); StrOp.free(releasename); StrOp.free(httpget); TraceOp.trc( "updates", TRCLEVEL_INFO, __LINE__, 9999, "Read response..." ); char str[1024] = {'\0'}; SocketOp.setRcvTimeout( sh, 1000 ); /* Read first HTTP header line: */ OK = false; SocketOp.readln( sh, str ); TraceOp.trc( "updates", TRCLEVEL_INFO, __LINE__, 9999, str ); if( StrOp.find( str, "200 OK" ) ) { OK = true; TraceOp.trc( "updates", TRCLEVEL_INFO, __LINE__, 9999, "OK" ); } /* Reading rest of HTTP header: */ int contlen = 0; while( SocketOp.readln( sh, str ) && !SocketOp.isBroken( sh ) ) { if( str[0] == '\r' || str[0] == '\n' ) { break; } if( StrOp.find( str, "Content-Length:" ) ) { char* p = StrOp.find( str, ": " ) + 2; contlen = atoi( p ); TraceOp.trc( "updates", TRCLEVEL_INFO, __LINE__, 9999, "contlen = %d", contlen ); } TraceOp.trc( "updates", TRCLEVEL_INFO, __LINE__, 9999, str ); }; if( OK && contlen > 0 ) { TraceOp.trc( "updates", TRCLEVEL_INFO, __LINE__, 9999, "downloading [%s]", wPatch.getfile(patch) ); char* release = (char*)allocMem(contlen+1); SocketOp.read( sh, release, contlen ); char* path = StrOp.fmt("%s%c%s.%s.%s.%d", wGui.getupdatespath(wxGetApp().getIni()), SystemOp.getFileSeparator(), wPatch.getfile(patch), wPatch.getos(patch), wRelease.getversion(o->m_ReleaseNode), wPatch.getnr(patch)); iOFile file = FileOp.inst(path, OPEN_WRITE ); if(file != NULL) { FileOp.write( file, release, contlen); FileOp.base.del(file); } StrOp.free(path); freeMem(release); } SocketOp.disConnect(sh); } else { TraceOp.trc( "updates", TRCLEVEL_WARNING, __LINE__, 9999, "could not connected to %s", wGui.getupdatesserver(wxGetApp().getIni()) ); } SocketOp.base.del(sh); } patch = wRelease.nextpatch(o->m_ReleaseNode, patch); } } o->setReady(OK); }
void updateReaderThread( void* threadinst ) { iOThread th = (iOThread)threadinst; Softwareupdates* o = (Softwareupdates*)ThreadOp.getParm( th ); bool newPatches = false; TraceOp.trc( "updates", TRCLEVEL_INFO, __LINE__, 9999, "updateReaderThread started" ); if( o == NULL ) { ThreadOp.sleep(5000); } else ThreadOp.sleep(100); TraceOp.trc( "updates", TRCLEVEL_INFO, __LINE__, 9999, "updateReaderThread try to connect with %s", wGui.getupdatesserver(wxGetApp().getIni()) ); iOSocket sh = SocketOp.inst( wGui.getupdatesserver(wxGetApp().getIni()), 80, False, False, False ); if( SocketOp.connect( sh ) ) { if( o != NULL ) o->setConnected(true); TraceOp.trc( "updates", TRCLEVEL_INFO, __LINE__, 9999, "Connected to rocrail.net" ); char* releasename = StrOp.dup(wGui.releasename); StrOp.replaceAll( releasename, ' ', '\0'); char* httpget = StrOp.fmt("GET /releases/%s.xml HTTP/1.1\nHost: www.rocrail.net\n\n", StrOp.strlwr( releasename ) ); TraceOp.trc( "updates", TRCLEVEL_INFO, __LINE__, 9999, "%s", httpget ); SocketOp.write( sh, httpget, StrOp.len(httpget) ); StrOp.free(releasename); StrOp.free(httpget); TraceOp.trc( "updates", TRCLEVEL_INFO, __LINE__, 9999, "Read response..." ); char str[1024] = {'\0'}; SocketOp.setRcvTimeout( sh, 1000 ); /* Read first HTTP header line: */ SocketOp.readln( sh, str ); TraceOp.trc( "updates", TRCLEVEL_INFO, __LINE__, 9999, str ); /* Reading rest of HTTP header: */ int contlen = 0; while( SocketOp.isConnected(sh) && !SocketOp.isBroken( sh ) && SocketOp.readln( sh, str ) ) { if( str[0] == '\r' || str[0] == '\n' ) { break; } if( StrOp.find( str, "Content-Length:" ) ) { char* p = StrOp.find( str, ": " ) + 2; contlen = atoi( p ); TraceOp.trc( "updates", TRCLEVEL_INFO, __LINE__, 9999, "contlen = %d", contlen ); } TraceOp.trc( "updates", TRCLEVEL_INFO, __LINE__, 9999, str ); }; if( SocketOp.isConnected(sh) && !SocketOp.isBroken( sh ) && contlen > 0 ) { char* release = (char*)allocMem(contlen+1); SocketOp.read( sh, release, contlen ); TraceOp.trc( "updates", TRCLEVEL_INFO, __LINE__, 9999, release ); iONode releasenode = __evaluate( release, &newPatches ); if( o != NULL ) o->m_ReleaseNode = releasenode; } SocketOp.disConnect(sh); } else { if( o != NULL ) o->setConnected(false); TraceOp.trc( "updates", TRCLEVEL_WARNING, __LINE__, 9999, "could not connected to %s", wGui.getupdatesserver(wxGetApp().getIni()) ); } if( newPatches ) { // inform toolbar TraceOp.trc( "updates", TRCLEVEL_INFO, __LINE__, 9999, "unviewed patches..." ); wxCommandEvent event( wxEVT_COMMAND_MENU_SELECTED, NEWUPDATES_EVENT ); wxPostEvent( wxGetApp().getFrame(), event ); } else { TraceOp.trc( "updates", TRCLEVEL_INFO, __LINE__, 9999, "no unviewed patches" ); } if( o != NULL ) o->setReady(true); SocketOp.base.del(sh); ThreadOp.base.del(th); TraceOp.trc( "updates", TRCLEVEL_INFO, __LINE__, 9999, "cleaned up thread" ); }
static Boolean __executeCmd(iONode cmd, iOMap map, const char* oid, Boolean* breakloop, Boolean* continueloop, iONode script) { Boolean exit = False; iOModel model = AppOp.getModel(); if( StrOp.equals("function", NodeOp.getName(cmd)) ) { TraceOp.trc( name, TRCLEVEL_INFO, __LINE__, 9999, "skip function [%s]", wItem.getid(cmd)); return exit; } TraceOp.trc( name, TRCLEVEL_INFO, __LINE__, 9999, "execute [%s] id[%s] cmd[%s] oid[%s] callerid[%s]", NodeOp.getName(cmd), wItem.getid(cmd), NodeOp.getStr(cmd, "cmd", "-"), oid!=NULL?oid:"", map != NULL ? (const char*)MapOp.get(map, "callerid"):"-" ); /* loco */ if( StrOp.equals( wFunCmd.name(), NodeOp.getName(cmd)) || StrOp.equals( wLoc.name(), NodeOp.getName(cmd)) || StrOp.equals( wCar.name(), NodeOp.getName(cmd)) ) { char* idRes = VarOp.getText(wItem.getid(cmd), map, ' '); iOLoc lc = ModelOp.getLoc(model, idRes, NULL, False); iOCar car = ModelOp.getCar(model, idRes); iIBlockBase bk = NULL; if( lc == NULL && (bk = ModelOp.getBlock(model, wItem.getid(cmd))) != NULL ) { TraceOp.trc( name, TRCLEVEL_INFO, __LINE__, 9999, "get loco id from block [%s]", wItem.getid(cmd) ); lc = ModelOp.getLoc(model, bk->getLoc(bk), NULL, False); } if( lc == NULL && NodeOp.getStr(cmd, "bkid", NULL) != NULL ) { char* bkidRes = VarOp.getText(NodeOp.getStr(cmd, "bkid", NULL), map, ' '); bk = ModelOp.getBlock(model, bkidRes); TraceOp.trc( name, TRCLEVEL_INFO, __LINE__, 9999, "get loco id from block [%s]", bkidRes ); lc = ModelOp.getLoc(model, bk->getLoc(bk), NULL, False); StrOp.free(bkidRes); } if( lc != NULL ) { iONode clone = (iONode)NodeOp.base.clone(cmd); wLoc.setid(clone, LocOp.getId(lc)); if( StrOp.equals( wFunCmd.name(), NodeOp.getName(cmd)) ) { int fnaction = wFunCmd.getfnchanged(cmd); if( wFunCmd.getfndesc(cmd) != NULL ) { fnaction = LocOp.getFnNrByDesc(lc, wFunCmd.getfndesc(cmd)); } if( fnaction != -1 ) { char fnkey[32]; wFunCmd.setfnchanged(clone, fnaction); StrOp.fmtb(fnkey, "f%d", fnaction); if( wFunCmd.getfncmd(cmd) != NULL ) { const char* fncmd = wFunCmd.getfncmd(cmd); if( StrOp.equals(wFunCmd.on, fncmd) ) NodeOp.setBool(clone, fnkey, True); else if( StrOp.equals(wFunCmd.off, fncmd) ) NodeOp.setBool(clone, fnkey, False); else if( StrOp.equals(wFunCmd.flip, fncmd) ) NodeOp.setBool(clone, fnkey, !LocOp.isFunction(lc, fnaction)); } } } if( wLoc.getblockid(clone) != NULL && StrOp.len(wLoc.getblockid(clone)) > 0 ) { char* bkidRes = VarOp.getText(wLoc.getblockid(clone), map, ' '); wLoc.setblockid(clone, bkidRes); StrOp.free(bkidRes); } if( wLoc.getscheduleid(clone) != NULL && StrOp.len(wLoc.getscheduleid(clone)) > 0 ) { char* scidRes = VarOp.getText(wLoc.getscheduleid(clone), map, ' '); wLoc.setscheduleid(clone, scidRes); StrOp.free(scidRes); } LocOp.cmd(lc, clone); } if( car != NULL ) { iONode clone = (iONode)NodeOp.base.clone(cmd); wCar.setid(clone, wCar.getid(CarOp.base.properties(car))); if( StrOp.equals( wFunCmd.name(), NodeOp.getName(cmd)) ) { int fnaction = wFunCmd.getfnchanged(cmd); if( wFunCmd.getfndesc(cmd) != NULL ) { fnaction = CarOp.getFnNrByDesc(car, wFunCmd.getfndesc(cmd)); } if( fnaction != -1 ) { char fnkey[32]; wFunCmd.setfnchanged(clone, fnaction); StrOp.fmtb(fnkey, "f%d", fnaction); if( wFunCmd.getfncmd(cmd) != NULL ) { const char* fncmd = wFunCmd.getfncmd(cmd); if( StrOp.equals(wFunCmd.on, fncmd) ) NodeOp.setBool(clone, fnkey, True); else if( StrOp.equals(wFunCmd.off, fncmd) ) NodeOp.setBool(clone, fnkey, False); else if( StrOp.equals(wFunCmd.flip, fncmd) ) NodeOp.setBool(clone, fnkey, !CarOp.isFunction(car, fnaction)); } } } CarOp.cmd(car, clone); } StrOp.free(idRes); } /* operator */ else if( StrOp.equals( wOperator.name(), NodeOp.getName(cmd)) ) { char* idRes = VarOp.getText(wItem.getid(cmd), map, ' '); iOOperator op = ModelOp.getOperator(model, idRes); if( op != NULL ) { OperatorOp.cmd(op, (iONode)NodeOp.base.clone(cmd)); } StrOp.free(idRes); } /* block */ else if( StrOp.equals( wBlock.name(), NodeOp.getName(cmd)) ) { char* idRes = VarOp.getText(wItem.getid(cmd), map, ' '); iIBlockBase bk = ModelOp.getBlock(model, idRes); if( bk != NULL ) { if( StrOp.equals(wAction.block_reserve, wBlock.getcmd(cmd) ) ) { char* lcidRes = VarOp.getText(wActionCtrl.getlcid(cmd), map, ' '); bk->lock( bk, lcidRes, NULL, NULL, False, False, False, 0, NULL, True); StrOp.free(lcidRes); } else { bk->cmd(bk, (iONode)NodeOp.base.clone(cmd)); } } StrOp.free(idRes); } /* stage */ else if( StrOp.equals( wStage.name(), NodeOp.getName(cmd)) ) { char* idRes = VarOp.getText(wItem.getid(cmd), map, ' '); iOStage stage = ModelOp.getStage(model, idRes); if( stage != NULL ) { StageOp.cmd( (iIBlockBase)stage, (iONode)NodeOp.base.clone(cmd)); } StrOp.free(idRes); } /* seltab */ else if( StrOp.equals( wSelTab.name(), NodeOp.getName(cmd)) ) { char* idRes = VarOp.getText(wItem.getid(cmd), map, ' '); iOSelTab seltab = ModelOp.getSelectiontable(model, idRes); if( seltab != NULL ) { SelTabOp.cmd( (iIBlockBase)seltab, (iONode)NodeOp.base.clone(cmd)); } StrOp.free(idRes); } /* location */ else if( StrOp.equals( wLocation.name(), NodeOp.getName(cmd)) ) { char* idRes = VarOp.getText(wItem.getid(cmd), map, ' '); iOLocation location = ModelOp.getLocation(model, idRes); if( location != NULL ) { LocationOp.cmd( location, (iONode)NodeOp.base.clone(cmd)); } StrOp.free(idRes); } /* switch */ else if( StrOp.equals( wSwitch.name(), NodeOp.getName(cmd)) ) { char* idRes = VarOp.getText(wItem.getid(cmd), map, ' '); iOSwitch sw = ModelOp.getSwitch(model, idRes); if( sw != NULL ) { SwitchOp.cmd(sw, (iONode)NodeOp.base.clone(cmd), True, 0, NULL, NULL); } StrOp.free(idRes); } /* signal */ else if( StrOp.equals( wSignal.name(), NodeOp.getName(cmd)) ) { char* idRes = VarOp.getText(wItem.getid(cmd), map, ' '); iOSignal sg = ModelOp.getSignal(model, idRes); if( sg != NULL ) { SignalOp.cmd(sg, (iONode)NodeOp.base.clone(cmd), True); } StrOp.free(idRes); } /* route */ else if( StrOp.equals( wRoute.name(), NodeOp.getName(cmd)) ) { char* idRes = VarOp.getText(wItem.getid(cmd), map, ' '); iORoute st = ModelOp.getRoute(model, idRes); if( NodeOp.findAttr(cmd, "locid") != NULL ) { char* locidRes = VarOp.getText(wRoute.getlocid(cmd), map, ' '); wRoute.setlocid(cmd, locidRes); StrOp.free(locidRes); } if( st != NULL ) { RouteOp.cmd(st, (iONode)NodeOp.base.clone(cmd)); } StrOp.free(idRes); } /* output */ else if( StrOp.equals( wOutput.name(), NodeOp.getName(cmd)) ) { char* idRes = VarOp.getText(wItem.getid(cmd), map, ' '); iOOutput co = ModelOp.getOutput(model, idRes); if( co != NULL ) { OutputOp.cmd(co, (iONode)NodeOp.base.clone(cmd), True); } StrOp.free(idRes); } /* sensor */ else if( StrOp.equals( wFeedback.name(), NodeOp.getName(cmd)) ) { char* idRes = VarOp.getText(wItem.getid(cmd), map, ' '); iOFBack fb = ModelOp.getFBack(model, idRes); if( fb != NULL ) { if( StrOp.equals(wOutput.flip, wFeedback.getcmd(cmd)) ) { Boolean state = FBackOp.getState(fb); wFeedback.setstate( cmd, !state ); TraceOp.trc( name, TRCLEVEL_INFO, __LINE__, 9999, "setting sensor [%s] to [%s]", idRes, state?"off":"on" ); FBackOp.event( fb, (iONode)NodeOp.base.clone(cmd) ); } else if( StrOp.equals(wOutput.on, wFeedback.getcmd(cmd)) || StrOp.equals(wOutput.off, wFeedback.getcmd(cmd)) ) { wFeedback.setstate( cmd, StrOp.equals(wOutput.on, wFeedback.getcmd(cmd)) ? True:False); TraceOp.trc( name, TRCLEVEL_INFO, __LINE__, 9999, "setting sensor [%s] to [%s]", idRes, wFeedback.getcmd(cmd) ); FBackOp.event( fb, (iONode)NodeOp.base.clone(cmd) ); } else { FBackOp.cmd(fb, (iONode)NodeOp.base.clone(cmd), True); } } StrOp.free(idRes); } /* actionctrl */ else if( StrOp.equals( wActionCtrl.name(), NodeOp.getName(cmd)) ) { iOAction Action = ModelOp.getAction(model, wActionCtrl.getid( cmd )); if( Action != NULL ) { ActionOp.exec(Action, cmd); } else TraceOp.trc( name, TRCLEVEL_WARNING, __LINE__, 9999, "action [%s] not found", wActionCtrl.getid( cmd ) ); } /* auto */ else if( StrOp.equals( wAutoCmd.name(), NodeOp.getName(cmd)) ) { clntcon_callback pfun = ControlOp.getCallback(AppOp.getControl()); pfun( (obj)AppOp.getControl(), (iONode)NodeOp.base.clone(cmd) ); } /* system */ else if( StrOp.equals( wSysCmd.name(), NodeOp.getName(cmd)) ) { int error = 0; ControlOp.cmd( AppOp.getControl(), (iONode)NodeOp.base.clone(cmd), &error ); } /* sleep */ else if( StrOp.equals( "sleep", NodeOp.getName(cmd)) ) { int sleep = VarOp.getValue(NodeOp.getStr(cmd, "time", "0"), NULL ); if( sleep > 1000 ) { TraceOp.trc( name, TRCLEVEL_WARNING, __LINE__, 9999, "a sleep > 1000ms, %d, is not permitted; Sleep 1000ms...", sleep ); sleep = 1000; } ThreadOp.sleep(sleep); } /* exit */ else if( StrOp.equals( "exit", NodeOp.getName(cmd)) ) { exit = True; TraceOp.trc( name, TRCLEVEL_INFO, __LINE__, 9999, "exit script: %s", NodeOp.getStr(cmd, "cmt", "?") ); } /* continue */ else if( StrOp.equals( "continue", NodeOp.getName(cmd)) ) { if( continueloop != NULL ) { const char* condition = NodeOp.getStr(cmd, "condition", NULL); char* conditionRes = NULL; if( condition != NULL ) { conditionRes = TextOp.replaceAllSubstitutions(condition, map); TraceOp.trc( name, TRCLEVEL_INFO, __LINE__, 9999, "continue condition [%s]", conditionRes ); } if( conditionRes == NULL || __isCondition(conditionRes, NodeOp.getBool(cmd, "alltrue", True)) ) { *continueloop = True; TraceOp.trc( name, TRCLEVEL_INFO, __LINE__, 9999, "continue: %s", NodeOp.getStr(cmd, "cmt", "?") ); } } } /* break */ else if( StrOp.equals( "break", NodeOp.getName(cmd)) ) { if( breakloop != NULL ) { const char* condition = NodeOp.getStr(cmd, "condition", NULL); char* conditionRes = NULL; if( condition != NULL ) { conditionRes = TextOp.replaceAllSubstitutions(condition, map); TraceOp.trc( name, TRCLEVEL_INFO, __LINE__, 9999, "break condition [%s]", conditionRes ); } if( conditionRes == NULL || __isCondition(conditionRes, NodeOp.getBool(cmd, "alltrue", True)) ) { *breakloop = True; TraceOp.trc( name, TRCLEVEL_INFO, __LINE__, 9999, "break: %s", NodeOp.getStr(cmd, "cmt", "?") ); } } } /* sub */ else if( StrOp.equals( "sub", NodeOp.getName(cmd)) ) { const char* scriptFile = NodeOp.getStr(cmd, "file", ""); char* xmlFilename = NULL; if( FileOp.isAbsolute(scriptFile) ) xmlFilename = StrOp.dup(scriptFile); else xmlFilename = StrOp.fmt("%s%c%s", wRocRail.getxmlscriptpath(AppOp.getIni()), SystemOp.getFileSeparator(), scriptFile); TraceOp.trc( name, TRCLEVEL_INFO, __LINE__, 9999, "sub xmlscript: [%s]", xmlFilename ); if( FileOp.exist(xmlFilename) ) { int size = FileOp.fileSize(xmlFilename); char* xmlscript = allocMem( size + 1); iOFile f = FileOp.inst( xmlFilename, OPEN_READONLY); if( f != NULL ) { FileOp.read( f, xmlscript, size); FileOp.base.del(f); TraceOp.trc( name, TRCLEVEL_INFO, __LINE__, 9999, "run sub xmlscript file [%s], size=%d", xmlFilename, size ); XmlScriptOp.run( xmlscript, map, wItem.getid(cmd) ); freeMem(xmlscript); } } StrOp.free(xmlFilename); } /* var */ else if( StrOp.equals( wVariable.name(), NodeOp.getName(cmd)) ) { iOMap map = MapOp.inst(); const char* id = wItem.getid(cmd); MapOp.put(map, "oid", (obj)oid); char* varRes = VarOp.getText(id, map, ' '); MapOp.base.del(map); iONode var = ModelOp.getVariable(model, varRes); if( var == NULL ) var = ModelOp.addVariable( model, varRes ); if( var != NULL ) { if( NodeOp.findAttr(cmd, "text") != NULL) { wVariable.settext(var, VarOp.getText(wVariable.gettext(cmd), NULL, wVariable.gettokeniser(cmd)[0])); TraceOp.trc( name, TRCLEVEL_INFO, __LINE__, 9999, "var [%s] = [%s]", varRes, wVariable.gettext(var) ); } if( NodeOp.findAttr(cmd, "value") != NULL ) { wVariable.setvalue(var, VarOp.getValue(NodeOp.getStr(cmd, "value", ""), NULL)); TraceOp.trc( name, TRCLEVEL_INFO, __LINE__, 9999, "var [%s] = %d", varRes, wVariable.getvalue(var) ); } if( NodeOp.findAttr(cmd, "min") != NULL ) { wVariable.setmin(var, NodeOp.getInt(cmd, "min", 0)); TraceOp.trc( name, TRCLEVEL_INFO, __LINE__, 9999, "var [%s] min = %d", varRes, wVariable.getmin(var) ); } if( NodeOp.findAttr(cmd, "max") != NULL ) { wVariable.setmax(var, NodeOp.getInt(cmd, "max", 0)); TraceOp.trc( name, TRCLEVEL_INFO, __LINE__, 9999, "var [%s] max = %d", varRes, wVariable.getmax(var) ); } if( NodeOp.findAttr(cmd, "cmd") != NULL ) { if( StrOp.equals(NodeOp.getStr(cmd, "cmd", ""), wVariable.op_random ) ) { VarOp.setRandom(var); } else if( StrOp.equals(NodeOp.getStr(cmd, "cmd", ""), wVariable.op_start ) ) { wVariable.settimer(var, True); TraceOp.trc( name, TRCLEVEL_CALC, __LINE__, 9999, "variable [%s] cmd=[%s] timer started with value %d", wVariable.getid(var), wVariable.op_start, wVariable.getvalue(var) ); } else if( StrOp.equals(NodeOp.getStr(cmd, "cmd", ""), wVariable.op_stop ) ) { wVariable.settimer(var, False); TraceOp.trc( name, TRCLEVEL_CALC, __LINE__, 9999, "variable [%s] cmd=[%s] timer stopped with value %d", wVariable.getid(var), wVariable.op_stop, wVariable.getvalue(var) ); } } /* Broadcast to clients. */ { iONode node = NodeOp.inst( wVariable.name(), NULL, ELEMENT_NODE ); wVariable.setid( node, wVariable.getid( var ) ); wVariable.settext( node, wVariable.gettext( var ) ); wVariable.setvalue( node, wVariable.getvalue( var ) ); wVariable.setmin( node, wVariable.getmin( var ) ); wVariable.setmax( node, wVariable.getmax( var ) ); TraceOp.trc( name, TRCLEVEL_INFO, __LINE__, 9999, "broadcast variable %s [%d, \"%s\"]", wVariable.getid(var), wVariable.getvalue(var), wVariable.gettext(var)); AppOp.broadcastEvent( node ); } } StrOp.free( varRes ); } /* text */ else if( StrOp.equals( wText.name(), NodeOp.getName(cmd)) ) { char* oid = VarOp.getText(wItem.getid(cmd), map, ' '); iOText text = ModelOp.getText( model, oid ); if( text != NULL && wText.getformat(cmd) != NULL ) { iONode evt = NodeOp.inst( wText.name(), NULL, ELEMENT_NODE ); wText.setformat(evt, wText.getformat(cmd)); if( map != NULL ) { if( MapOp.haskey(map, "lcid") ) wText.setreflcid(evt, (const char*)MapOp.get(map, "lcid")); if( MapOp.haskey(map, "bkid") ) wText.setrefbkid(evt, (const char*)MapOp.get(map, "bkid")); if( MapOp.haskey(map, "callerid") ) wText.setrefcallerid(evt, (const char*)MapOp.get(map, "callerid")); if( MapOp.haskey(map, "state") ) NodeOp.setStr(evt, "state", (const char*)MapOp.get(map, "state")); if( MapOp.haskey(map, "substate") ) NodeOp.setStr(evt, "substate", (const char*)MapOp.get(map, "substate")); } TextOp.base.event(text, evt); } else if( text != NULL && wText.getformat(cmd) == NULL ) { TraceOp.trc( name, TRCLEVEL_WARNING, __LINE__, 9999, "text [%s] format is missing", oid); } else if( text == NULL ) { TraceOp.trc( name, TRCLEVEL_WARNING, __LINE__, 9999, "text [%s] not found", oid); } StrOp.free(oid); } /* if */ else if( StrOp.equals( "if", NodeOp.getName(cmd)) ) { TraceOp.trc( name, TRCLEVEL_INFO, __LINE__, 9999, "nested if..."); exit = __doIf(cmd, map, script); } /* foreach */ else if( StrOp.equals( "foreach", NodeOp.getName(cmd)) ) { TraceOp.trc( name, TRCLEVEL_INFO, __LINE__, 9999, "nested foreach..."); exit = __doForEach(cmd, map, script); } /* while */ else if( StrOp.equals( "while", NodeOp.getName(cmd)) ) { TraceOp.trc( name, TRCLEVEL_INFO, __LINE__, 9999, "nested while..."); exit = __doWhile(cmd, map, script); } /* switch */ else if( StrOp.equals( "switch", NodeOp.getName(cmd)) ) { TraceOp.trc( name, TRCLEVEL_INFO, __LINE__, 9999, "nested switch..."); exit = __doSwitch(cmd, map, script); } /* call */ else if( StrOp.equals( "call", NodeOp.getName(cmd)) ) { TraceOp.trc( name, TRCLEVEL_INFO, __LINE__, 9999, "call..."); exit = __doCall(cmd, map, script); } return exit; }
/** ------------------------------------------------------------ * public main() * * @param argc Number of commanline arguments. * @param argv Commanline arguments. * @return Applications exit code. */ int main( int argc, const char* argv[] ) { int rc = 0; iOTrace trc = TraceOp.inst( TRCLEVEL_INFO, "xml2cstr", True ); TraceOp.setAppID( trc, "x" ); /* Enable coredump for Linux platforms. */ #if defined __linux__ { struct rlimit rl; getrlimit( RLIMIT_CORE, &rl ); /* Default = 0 */ rl.rlim_cur = 10240 * 10240; setrlimit( RLIMIT_CORE, &rl ); } #endif /* Resets memory statistics. */ MemOp.resetDump(); /* Read const.xml */ if( argc >= 4 && FileOp.exist(argv[1]) ) { TraceOp.println( "Converting [%s] into a \"C\" strting [%s], named as [%s]", argv[1], argv[2], argv[3] ); { iOFile msgXml = FileOp.inst( argv[1], OPEN_READONLY ); iOFile msgStr = FileOp.inst( argv[2], OPEN_WRITE ); if( msgXml == NULL || msgStr == NULL ) return -1; else { unsigned char* inBuffer = allocMem( 1 * BUFFERSIZE ); unsigned char* outBuffer = allocMem( 2 * BUFFERSIZE ); long infileLen = FileOp.size( msgXml ); long readed = 0; FileOp.fmt( msgStr, "#ifdef __cplusplus\n extern \"C\" {\n#endif\n\n" ); FileOp.fmt( msgStr, "const char %s[] = {\n", argv[3] ); while( readed != infileLen ) { long toRead = BUFFERSIZE <= infileLen - readed ? BUFFERSIZE:(infileLen - readed); if( FileOp.read( msgXml, (char*)inBuffer, toRead ) ) { int i = 0; int len = 0; readed += toRead; for( i = 0; i < toRead; i++ ) { if( inBuffer[i] == '\r' ) continue; else { FileOp.fmt( msgStr, "%d,", inBuffer[i] ); if (inBuffer[i] > 99) len += 3; else if (inBuffer[i] > 9) len += 2; else len++; } if( len > 50 ) { len = 0; FileOp.write( msgStr, "\n", 1 ); } } } else { TraceOp.println( "Error reading [%]! read=%ld infileLen=%ld", argv[1], readed, infileLen ); break; } } FileOp.fmt( msgStr, "%d\n};\n", 0 ); FileOp.fmt( msgStr, "#ifdef __cplusplus\n }\n#endif\n\n" ); FileOp.close( msgXml ); FileOp.base.del( msgXml ); FileOp.close( msgStr ); FileOp.base.del( msgStr ); freeMem( inBuffer ); freeMem( outBuffer ); } } } else { TraceOp.println( "Usage: xml2cstr input.xml output.c strname" ); } return rc; }
static void __evaluateRecord(iOGOT got, const char* msg) { iOGOTData data = Data(got); iOStrTok tok = StrTokOp.inst( msg, ',' ); char ident[32]; int idx = 0; int t = 0; int x = 0; int y = 0; int z = 0; int sid = 0; int valid = 0; TraceOp.trc( name, TRCLEVEL_BYTE, __LINE__, 9999, "record: [%s]", msg ); /* report to the Rocrail server */ while( StrTokOp.hasMoreTokens( tok ) ) { int val = atoi( StrTokOp.nextToken(tok) ); switch( idx ) { case 0: t = val; break; case 1: sid = val; break; case 2: valid = val; break; case 3: x = val; break; case 4: y = val; break; case 5: z = val; break; } idx++; }; StrTokOp.base.del(tok); StrOp.fmtb(ident, "%d", sid); if( valid ) { Boolean newSid = False; iOSender sender = (iOSender)MapOp.get(data->sidMap, ident ); if( sender == NULL ) { sender = allocMem( sizeof( struct sender) ); sender->sid = sid; sender->x = x; sender->y = y; sender->z = z; MapOp.put(data->sidMap, ident, (obj)sender); newSid = True; } if( newSid || sender->x != x || sender->y != y || sender->z != z ) { iONode nodeC = NodeOp.inst( wFeedback.name(), NULL, ELEMENT_NODE ); wFeedback.setgpstime( nodeC, t ); wFeedback.setgpssid( nodeC, sid ); wFeedback.setgpsx( nodeC, x ); wFeedback.setgpsy( nodeC, y ); wFeedback.setgpsz( nodeC, z ); wFeedback.setfbtype( nodeC, wFeedback.fbtype_gps ); if( data->iid != NULL ) wFeedback.setiid( nodeC, data->iid ); wFeedback.setstate( nodeC, True ); wFeedback.setidentifier( nodeC, ident); TraceOp.trc( name, TRCLEVEL_INFO, __LINE__, 9999, "t=%d sid=%d x=%d y=%d z=%d", t, sid, x, y, z ); data->listenerFun( data->listenerObj, nodeC, TRCLEVEL_INFO ); sender->x = x; sender->y = y; sender->z = z; } } }
w_int loadSuperClasses(w_clazz clazz, w_thread thread) { w_clazz super; w_int i; w_int n; w_int result = CLASS_LOADING_DID_NOTHING; #ifndef NO_FORMAT_CHECKS if (isNotSet(clazz->flags, CLAZZ_IS_TRUSTED) && !clazz->temp.super_index) { throwException(thread, clazzVerifyError, "Class %k has no superclass", clazz); return CLASS_LOADING_FAILED; } #endif clazz->supers = allocMem(MAX_SUPER_CLASSES * sizeof(w_clazz)); if (!clazz->supers) { return CLASS_LOADING_FAILED; } super = clazz; n = MAX_SUPER_CLASSES; for (i = 0; i < MAX_SUPER_CLASSES; ++i) { if (!super->temp.super_index) { woempa(1, "Reached top of hierarchy after %d class(es): %k\n", i, super); n = i; break; } #ifndef NO_FORMAT_CHECKS if (isNotSet(super->flags, CLAZZ_IS_TRUSTED) && !isClassConstant(super, super->temp.super_index)) { throwException(thread, clazzClassFormatError, "Superclass of %k is not a class constant (is %02x)", super, super->tags[super->temp.super_index]); return CLASS_LOADING_FAILED; } #endif super = getClassConstant(super, super->temp.super_index, thread); if (!super) { throwException(thread, clazzLinkageError, "Cannot resolve superclass of %k", clazz); return CLASS_LOADING_FAILED; } clazz->supers[i] = super; woempa(1, "Class %k supers[%d] = %k\n", clazz, i, super); if (getClazzState(super) >= CLAZZ_STATE_SUPERS_LOADED) { woempa(1, "Class %k is already supersLoaded, has %d superclasses => depth of %k is %d\n", super, super->numSuperClasses, clazz, i + super->numSuperClasses + 1); n = i + super->numSuperClasses + 1; break; } } if (n == MAX_SUPER_CLASSES) { wabort(ABORT_WONKA, "Class %k has too many superclasses", clazz); } for (i= i + 1; i < n; ++i) { woempa(1, "Copying %k (superclass[%d] of %k) as superclass[%d] of %k\n", super->supers[i - n + super->numSuperClasses], i - n + super->numSuperClasses, super, i, clazz); clazz->supers[i] = super->supers[i - n + super->numSuperClasses]; } woempa(1, "Class %k has total of %d superclasses\n", clazz, n); clazz->supers = reallocMem(clazz->supers, n * sizeof(w_clazz)); if (!clazz->supers) { return CLASS_LOADING_FAILED; } clazz->numSuperClasses = n; super = clazz->supers[0]; #ifndef NO_HIERARCHY_CHECKS if (isNotSet(super->flags, CLAZZ_IS_TRUSTED)) { if (isSet(clazz->flags, ACC_INTERFACE) && super != clazzObject) { throwException(thread, clazzIncompatibleClassChangeError, "Superclass %k of %k is an interface", super, clazz); return CLASS_LOADING_FAILED; } if (isSet(super->flags, ACC_FINAL)) { woempa(9, "Violation of J+JVM Constraint 4.1.1, item 2\n"); throwException(thread, clazzIncompatibleClassChangeError, "Superclass %k of %k is final", super, clazz); return CLASS_LOADING_FAILED; } if (isNotSet(super->flags, ACC_PUBLIC) && !sameRuntimePackage(clazz, super)) { woempa(9, "Violation of J+JVM Constraint 4.1.4\n"); throwException(thread, clazzIncompatibleClassChangeError, "Superclass %k of %k is not accessible", super, clazz); return CLASS_LOADING_FAILED; } } #endif for (i = n - 1; i >= 0; --i) { result |= mustBeSupersLoaded(clazz->supers[i]); if (result == CLASS_LOADING_FAILED || exceptionThrown(thread)) { return CLASS_LOADING_FAILED; } } clazz->flags |= super->flags & CLAZZ_HERITABLE_FLAGS; return CLASS_LOADING_SUCCEEDED; }
int main0( int argc, char *argv[] ) { int hyperthreading = -1; unsigned int threadsCount = 0; pthread_t dummy; char inputBuf[ BUFSZ ]; char * inputBufPtr = inputBuf; size_t inputBufLeft = 0; bz_stream_state_bs savedState; int wasStateSaved = 0; #ifdef NICKEDIT /*Nick adding read and write from files*/ FILE * infile; if (argc < 4) { fprintf( stderr, helpText ); return 1; } #endif int x; /* Parse arguments */ for( x = 1; x < argc; ++x ) { if ( !strcmp( argv[ x ], "--help" ) ) { fprintf( stderr, helpText ); return 1; } if ( !strcmp( argv[ x ], "--ht" ) ) { hyperthreading = 1; continue; } if ( !strcmp( argv[ x ], "--no-ht" ) ) { hyperthreading = 0; continue; } if ( argv[ x ][ 0 ] == '-' ) { char * p = argv[ x ] + 1; char c; do { c = *p++; if ( c >= '1' && c <= '9' ) { blockSize100k = c - '1' + 1; } else if ( c == 'p' ) { if ( sscanf( p, "%u", &threadsCount ) != 1 ) { printf("Error parsing the number of threads passed: %s.\n", argv[ x ] + 2 ); return 1; } c = 0; /* We don't support parsing past -p# */ } else if ( c == 'v' ) { ++verbosityLevel; } else break; } while( c ); if ( !c ) continue; } #ifdef NICKEDIT break; #endif printf("Unrecognized option %s passed.\n", argv[ x ] ); return 1; } #ifdef NICKEDIT #else if ( isatty ( fileno ( stdout ) ) ) { printf("Won't write compressed data to a terminal. Use --help to get help.\n" ); return 1; } #endif if ( !threadsCount ) { x = sysconf( _SC_NPROCESSORS_ONLN ); if ( x == -1 ) { printf("Failed to get the number of processors in the system: %s", strerror( errno ) ); return 1; } threadsCount = x; if ( hyperthreading == -1 ) hyperthreading = isHtPresent(); if ( hyperthreading ) threadsCount /= 2; printf("CPUs detected: %d\n", threadsCount ); } printf("Threads to use: %d\n", threadsCount ); /* Allocate the input chunks buffer. The actual input chunks are malloc()ed dynamically, since they are consumed randomly. The inChunksFree variable holds the number of chunks we can malloc(). */ inChunksCount = threadsCount * 2; inChunksFree = inChunksCount; inChunks = ( bz_stream ** ) allocMem( sizeof( bz_stream * ) * inChunksCount ); /* Ok, now allocate output chunks */ outChunksCount = threadsCount * 2 + 1; outChunks = ( bz_stream ** ) allocMem( sizeof( bz_stream * ) * outChunksCount ); for( x = outChunksCount; x--; ) outChunks[ x ] = NULL; /* Output chunks allocated. */ /* Create compression threads */ for( x = 0; x < (int)threadsCount; ++x ) { if ( pthread_create( &dummy, NULL, &threadFunction, NULL ) ) { printf("Failed to create compression thread(s).\n" ); return 1; } } /* All compression threads started, and are waiting for some data to eat. */ /* Start the writer thread */ if ( pthread_create( &dummy, NULL, &writerThread, NULL ) ) { printf("Failed to create writer thread.\n" ); return 1; } /* This main thread acts only as a data reader. The compression threads pick the data up and process it, and the writer thread writes down the results.*/ #ifdef NICKEDIT /*Nick adds file read and write*/ printf("Opening file %s\n", argv[3]); infile = fopen(argv[3], "r"); nullout = fopen("/dev/null", "w"); #endif for( ; ; ) { bz_stream * strm = (bz_stream *)allocMem( sizeof( bz_stream ) ); int lastBlock = 1; /* Get an input chunk to place input data to */ pthread_mutex_lock( &inChunksMutex ); if ( !inChunksFree ) { /* No input chunks currently available, wait for one to become free */ pthread_cond_wait( &inChunksFreeCondition, &inChunksMutex ); } /* We just use it without advancing the head. Since we're the only one who store to the head, it is safe */ inChunks[ inChunksHead ] = strm; pthread_mutex_unlock( &inChunksMutex ); /* Init the compression */ strm->bzalloc = NULL; strm->bzfree = NULL; strm->opaque = NULL; x = BZ2_bzCompressInit ( strm, blockSize100k, 0, 0, 1 ); if ( x != BZ_OK ) { printf("bzip2 compress init returned error code %d\n", x ); exit( 1 ); } /* Any and all output data will be produced in a writer thread */ strm->avail_out = 0; if ( wasStateSaved ) BZ2_bzCompressRestoreState( strm, &savedState ); /* Feed the compressor until it can't handle more */ for( ; ; ) { if ( inputBufLeft ) { strm->next_in = inputBufPtr; strm->avail_in = inputBufLeft; x = BZ2_bzCompress( strm, BZ_RUN|BZ_STOP_BEFORE_BLOCKSORT ); if ( x == BZ_STOPPED_BEFORE_BLOCKSORT ) { /* The compressor can't handle no more. Leave the rest to the compression thread */ inputBufLeft = strm->avail_in; inputBufPtr = strm->next_in; lastBlock = 0; break; } if ( x != BZ_RUN_OK ) { printf("bzip2 compressing routine (input) returned " "error code %d\n", x ); return 1; } else inputBufLeft = 0; } else { #ifdef NICKEDIT inputBufLeft = fread( inputBuf, 1, sizeof( inputBuf ), infile); #else inputBufLeft = fread( inputBuf, 1, sizeof( inputBuf ), stdin ); #endif if ( !inputBufLeft ) { /* eof or error */ #ifdef NICKEDIT if ( feof( infile) ) #else if ( feof( stdin ) ) #endif { break; } else { /* 0 bytes read, and not on feof -- must be ferror */ #ifdef NICKEDIT printf("error reading data from file\n" ); #else printf("error reading data from stdin\n" ); #endif return 1; } } inputBufPtr = inputBuf; } } if ( !lastBlock ) { /* Save the state for the future blocks */ BZ2_bzCompressSaveStateBeforeBlocksort( strm, &savedState ); wasStateSaved = 1; } else { /* Finish up the block, so it goes to the blocksort stage */ strm->avail_in = 0; x = BZ2_bzCompress( strm, BZ_FINISH|BZ_STOP_BEFORE_BLOCKSORT ); if ( x != BZ_STOPPED_BEFORE_BLOCKSORT ) { printf("Error: bzip2 compressing routine (finish) " "returned error code %d\n", x ); return 1; } } /* Save the info on whether more blocks will follow or not. This would be used to either run or finish the stream */ /* We reuse avail_in. Way easier than putting our own superstruct. */ strm->avail_in = lastBlock; /* We have made an input chunk on the input chunk ring buffer, now let's present it */ pthread_mutex_lock( &inChunksMutex ); if ( inChunksTail == -1 ) { inChunksTail = inChunksHead; pthread_cond_signal( &inChunksAvailableCondition ); } ++inChunksHead; if ( inChunksHead == inChunksCount ) inChunksHead = 0; --inChunksFree; pthread_mutex_unlock( &inChunksMutex ); if ( lastBlock ) break; } /* Now that the data is all read, just wait until all in chunks are consumed and out chunks are written. */ printf("waiting for jobs to finish\n" ); pthread_mutex_lock( &inChunksMutex ); while ( inChunksFree != inChunksCount ) pthread_cond_wait( &inChunksFreeCondition, &inChunksMutex ); pthread_mutex_unlock( &inChunksMutex ); pthread_mutex_lock( &outChunksMutex ); while ( outChunksTail != -1 ) pthread_cond_wait( &outChunksAvailableCondition, &outChunksMutex ); pthread_mutex_unlock( &outChunksMutex ); /* Done */ printf("Done.\n"); /* No further semantic cleanup is required. Don't care freeing up the resources, the OS must do it anyway. */ done = 1; pthread_mutex_lock( &outChunksMutex ); pthread_mutex_lock( &inChunksMutex ); done = 1; pthread_cond_broadcast( &outChunksAvailableCondition ); pthread_cond_broadcast( &outChunksFlushCondition ); pthread_cond_broadcast( &inChunksAvailableCondition ); pthread_mutex_unlock( &outChunksMutex ); pthread_mutex_unlock( &inChunksMutex ); return 0; }
static iOP50 _inst( const iONode settings, const iOTrace trace ) { iOP50 p50 = allocMem( sizeof( struct OP50 ) ); iOP50Data data = allocMem( sizeof( struct OP50Data ) ); iOAttr attr = NULL; const char* flow = NULL; const char* parity = NULL; int i; for (i=0; i<81; i++) { dir6021[i]=1; } TraceOp.set( trace ); /* OBase */ MemOp.basecpy( p50, &P50Op, 0, sizeof( struct OP50 ), data ); data->mux = MutexOp.inst( StrOp.fmt( "serialMux%08X", data ), True ); /* Evaluate attributes. */ data->ini = settings; data->device = StrOp.dup( wDigInt.getdevice( settings ) ); data->iid = StrOp.dup( wDigInt.getiid( settings ) ); data->bps = wDigInt.getbps( settings ); data->bits = wDigInt.getbits( settings ); data->stopBits = wDigInt.getstopbits( settings ); data->timeout = wDigInt.gettimeout( settings ); data->fbmod = wDigInt.getfbmod( settings ); data->swtime = wDigInt.getswtime( settings ); data->psleep = wDigInt.getpsleep( settings); data->dummyio = wDigInt.isdummyio( settings ); data->ctsretry = wDigInt.getctsretry( settings ); data->readfb = wDigInt.isreadfb( settings ); data->run = True; data->serialOK = False; data->initOK = False; data->lastSwCmd = -1; parity = wDigInt.getparity( settings ); flow = wDigInt.getflow( settings ); if( StrOp.equals( wDigInt.even, parity ) ) data->parity = even; else if( StrOp.equals( wDigInt.odd, parity ) ) data->parity = odd; else if( StrOp.equals( wDigInt.none, parity ) ) data->parity = none; if( StrOp.equals( wDigInt.dsr, flow ) ) data->flow = dsr; else if( StrOp.equals( wDigInt.cts, flow ) ) data->flow = cts; else if( StrOp.equals( wDigInt.xon, flow ) ) data->flow = xon; else data->flow = 0; TraceOp.trc( name, TRCLEVEL_INFO, __LINE__, 9999, "----------------------------------------" ); TraceOp.trc( name, TRCLEVEL_INFO, __LINE__, 9999, "p50 %d.%d.%d", vmajor, vminor, patch ); TraceOp.trc( name, TRCLEVEL_INFO, __LINE__, 9999, "----------------------------------------" ); TraceOp.trc( name, TRCLEVEL_INFO, __LINE__, 9999, "iid = %s", data->iid ); TraceOp.trc( name, TRCLEVEL_INFO, __LINE__, 9999, "device = %s", data->device ); TraceOp.trc( name, TRCLEVEL_INFO, __LINE__, 9999, "baudrate = %d", data->bps ); TraceOp.trc( name, TRCLEVEL_INFO, __LINE__, 9999, "bits = %d", data->bits ); TraceOp.trc( name, TRCLEVEL_INFO, __LINE__, 9999, "stop bits = %d", data->stopBits ); TraceOp.trc( name, TRCLEVEL_INFO, __LINE__, 9999, "flow = %s", flow ); TraceOp.trc( name, TRCLEVEL_INFO, __LINE__, 9999, "timeout = %d", data->timeout ); TraceOp.trc( name, TRCLEVEL_INFO, __LINE__, 9999, "ctsretry = %d", data->ctsretry ); TraceOp.trc( name, TRCLEVEL_INFO, __LINE__, 9999, "readfb = %d", data->readfb ); TraceOp.trc( name, TRCLEVEL_INFO, __LINE__, 9999, "fbmod = %d", data->fbmod ); TraceOp.trc( name, TRCLEVEL_INFO, __LINE__, 9999, "poll sleep = %d", data->psleep ); TraceOp.trc( name, TRCLEVEL_INFO, __LINE__, 9999, "swtime = %d", data->swtime ); TraceOp.trc( name, TRCLEVEL_INFO, __LINE__, 9999, "----------------------------------------" ); data->serial = SerialOp.inst( data->device ); SerialOp.setFlow( data->serial, data->flow ); SerialOp.setLine( data->serial, data->bps, data->bits, data->stopBits, data->parity, wDigInt.isrtsdisabled( settings ) ); SerialOp.setTimeout( data->serial, data->timeout, data->timeout ); data->serialOK = SerialOp.open( data->serial ); if( data->serialOK ) { if( data->readfb ) { data->feedbackReader = ThreadOp.inst( "feedbackReader", &__feedbackReader, p50 ); ThreadOp.start( data->feedbackReader ); } data->swTimeWatcher = ThreadOp.inst( "swTimeWatcher", &__swTimeWatcher, p50 ); ThreadOp.start( data->swTimeWatcher ); } else { TraceOp.trc( name, TRCLEVEL_EXCEPTION, __LINE__, 9999, "Could not init p50 port!" ); } instCnt++; return p50; }
/*Main program*/ int main (int argc, char **argv) { int curarg = 1; int interactive = 0; char configurationFileName[128]; char choice = 'c'; char inputFileName[128]; char *outputFileName; FILE *inputFile = stdin; FILE *outputFile = stdout; int ch = 0; widechar *outbufx; int outlenx; int k; strcpy (configurationFileName, "default.cfg"); strcpy (inputFileName, "stdin"); outputFileName = "stdout"; if (argc > curarg) if (argv[curarg][0] == '-') { if ((argv[curarg][1] | 32) == 'h') { printf ("Usage: devonly [-f configFile] [inputFile] [outputFile]\n"); printf ("ConfigFile: configuration file name, default: ~/devonly.cfg.\n"); printf ("inputFile : input file, '-' means stdin\n"); printf ("outputFile : output file\n"); printf ("devonly with no argumenst takes input on stdin\n"); printf ("and gives output on stdout.\n"); exit (0); } else if ((argv[curarg][1] | 32) == 'f' && argc > (curarg + 1)) { strcpy (configurationFileName, argv[curarg + 1]); curarg = 3; } else if ((argv[curarg][1] | 32) == 'i') { interactive = 1; curarg = 100; } else { fprintf (stderr, "Invalid option %s.\n", argv[curarg]); exit (1); } } if (argc > curarg) { if (argv[curarg][0] != '-') strcpy (inputFileName, argv[curarg]); else { if ((argv[curarg][1] | 32) == 'i') { interactive = 1; curarg = 100; } else { fprintf (stderr, "Invalid option %s\n", argv[curarg]); exit (1); } } curarg++; } if (argc > curarg) outputFileName = argv[curarg]; do { if (interactive) { int namelen = 0; switch (choice) { case 'c': printf ("Enter the name of a configuration file.\n"); fgets (configurationFileName, sizeof (configurationFileName), stdin); configurationFileName[strlen (configurationFileName) - 1] = 0; choice = 'i'; continue; case 'i': printf ("Enter the name of an input file, or q to quit or c for a configuration file.\n"); fgets (inputFileName, sizeof (inputFileName), stdin); namelen = strlen (inputFileName) - 1; inputFileName[namelen] = 0; if (namelen == 1) { if (*inputFileName == 'q') interactive = 0; else if (*inputFileName == 'c') { choice = 'c'; continue; } } break; } if (!interactive) break; } /*Read file into memory*/ if (strcmp (inputFileName, "stdin") != 0) { if (!(inputFile = fopen (inputFileName, "r"))) { fprintf (stderr, "Can't open file %s.\n", inputFileName); if (!interactive) exit (1); else continue; } } else inputFile = stdin; if (outputFileName != "stdout") { if (!(outputFile = fopen (outputFileName, "w"))) { fprintf (stderr, "Can't open file %s.\n", outputFileName); if (!interactive) exit (1); else continue; } } else outputFile = stdout; memSize = STARTSIZE; memArea = NULL; memUsed = 0; allocMem (); while ((ch = fgetc (inputFile)) != EOF) { if (ch == 13) continue; memArea[memUsed++] = ch; if ((memUsed + 4) > memSize) allocMem (); } memArea[memUsed] = 0; if (inputFile != stdin) fclose (inputFile); outbufx = malloc (memSize); outlenx = memSize; if (lbx_translateString (configurationFileName, memArea, outbufx, &outlenx, 0) < 0) printf ("Error 1\n"); outlenx = memSize; if (lbx_translateString (configurationFileName, memArea, outbufx, &outlenx, 1) < 0) printf ("error 2\n"); for (k = 0; k < outlenx; k++) fputc ((char) outbufx[k], outputFile); if (outputFile != stdout) fclose (outputFile); free (memArea); free (outbufx); } while (interactive); lbx_free (); return 0; }
/* Returns number of messages fetched */ int fetchMail(int account) { const struct MACCOUNT *a = accounts + account - 1; const char *login = a->login; const char *pass = a->password; int nfetch = 0; /* number of messages actually fetched */ CURLcode res_curl = CURLE_OK; char *mailbox_url = get_mailbox_url(a); const char *url_for_error = mailbox_url; char *message_url = NULL; int message_count = 0, message_number; if (!mailDir) i_printfExit(MSG_NoMailDir); if (chdir(mailDir)) i_printfExit(MSG_NoDirChange, mailDir); if (!umf) { umf = allocMem(strlen(mailUnread) + 12); sprintf(umf, "%s/", mailUnread); umf_end = umf + strlen(umf); } unreadBase = 0; unreadStats(); mailstring = initString(&mailstring_l); CURL *mail_handle = newFetchmailHandle(mailbox_url, login, pass); res_curl = count_messages(mail_handle, mailbox_url, &message_count); if (res_curl != CURLE_OK) goto fetchmail_cleanup; for (message_number = 1; message_number <= message_count; message_number++) { if (asprintf(&message_url, "%s%u", mailbox_url, message_number) == -1) { /* Again, the byte count in the error message is a bit of a fib. */ i_printfExit(MSG_MemAllocError, strlen(mailbox_url) + 11); } nzFree(mailstring); mailstring = initString(&mailstring_l); res_curl = fetchOneMessage(mail_handle, message_url, message_number); if (res_curl != CURLE_OK) goto fetchmail_cleanup; nfetch++; res_curl = deleteOneMessage(mail_handle, message_url); if (res_curl != CURLE_OK) goto fetchmail_cleanup; nzFree(message_url); message_url = NULL; } fetchmail_cleanup: if (message_url) url_for_error = message_url; if (res_curl != CURLE_OK) { ebcurl_setError(res_curl, url_for_error); showError(); } curl_easy_cleanup(mail_handle); nzFree(message_url); nzFree(mailbox_url); nzFree(mailstring); mailstring = initString(&mailstring_l); return nfetch; } /* fetchMail */
int lspToLua(const char *rootDir, const char *lspFileName, const char *workDir, const char *luaFileName) { FILE *file; int lspLen; unsigned char *buff; int start, code, i, k; char *lspPath = fullPath(rootDir, lspFileName); char *luaPath = fullPath(workDir, luaFileName); if (fileIsNewer(lspPath, luaPath) == 0) { freeMem(lspPath); freeMem(luaPath); return 0; } file = fopen(lspPath, "r"); if (file == NULL) { error("cannot open %s\n", lspPath); freeMem(lspPath); freeMem(luaPath); return -1; } if (fseek(file, 0, SEEK_END) < 0) { error("cannot seek to end of %s\n", lspPath); fclose(file); freeMem(lspPath); freeMem(luaPath); return -1; } lspLen = ftell(file); if (lspLen < 0) { error("cannot determine length of %s\n", lspPath); fclose(file); freeMem(lspPath); freeMem(luaPath); return -1; } if (fseek(file, 0, SEEK_SET) < 0) { error("cannot seek to beginning of %s\n", lspPath); fclose(file); freeMem(lspPath); freeMem(luaPath); return -1; } buff = allocMem(lspLen); if (fread(buff, lspLen, 1, file) != 1) { error("cannot read %s\n", lspPath); fclose(file); freeMem(lspPath); freeMem(luaPath); freeMem(buff); return -1; } fclose(file); if (createAllDirs(luaPath) < 0) { error("cannot create required directories for %s\n", luaPath); freeMem(lspPath); freeMem(luaPath); freeMem(buff); return -1; } file = fopen(luaPath, "w"); if (file == NULL) { error("cannot open %s\n", luaPath); freeMem(lspPath); freeMem(luaPath); freeMem(buff); return -1; } start = 0; code = 0; i = 0; for (;;) { if (code == 0 && (i == lspLen || strncmp((char *)(buff + i), "<?lua", 5) == 0)) { fprintf(file, "tas.write(\""); for (k = start; k < i; k++) { if (buff[k] == 13) continue; if (buff[k] == '\\' || buff[k] == '"' || buff[k] == 10) fputc('\\', file); fputc(buff[k], file); } fprintf(file, "\")\n"); if (i == lspLen) break; if (buff[i + 5] == '=') { i += 6; code = 2; } else { i += 5; code = 1; } start = i; continue; } if (code > 0 && (i == lspLen || strncmp((char *)(buff + i), "?>", 2) == 0)) { if (code > 1) fprintf(file, "tas.write("); for (k = start; k < i; k++) if (buff[k] != 13) fputc(buff[k], file); if (code > 1) fputc(')', file); fputc('\n', file); if (i == lspLen) break; i += 2; start = i; code = 0; continue; } i++; } fclose(file); freeMem(lspPath); freeMem(luaPath); freeMem(buff); return 0; }
/* Return 0 for ok, 1 to delete the mail, -1 to stop. * stop is only meaningful for imap. */ static int presentMail(void) { int j, k; const char *redirect = NULL; /* send mail elsewhere */ char key = 0; const char *atname = NULL; /* name of file or attachment */ bool delflag = false; /* delete this mail */ bool scanat = false; /* scan for attachments */ int displine; int stashNumber = -1; /* clear things out from the last message */ if (lastMailInfo) freeMailInfo(lastMailInfo); lastMailInfo = 0; if (sessionList[1].lw) cxQuit(1, 2); cs = 0; cxSwitch(1, false); iuReformat(mailstring, mailstring_l, &mailu8, &mailu8_l); if (mailu8) { if (!addTextToBuffer((pst) mailu8, mailu8_l, 0, false)) showErrorAbort(); } else { if (!addTextToBuffer((pst) mailstring, mailstring_l, 0, false)) showErrorAbort(); } browseCurrentBuffer(); if (!passMail) { redirect = mailRedirect(lastMailInfo->to, lastMailInfo->from, lastMailInfo->reply, lastMailInfo->subject); } if (redirect) { if (!isimap) { delflag = true; key = 'w'; if (*redirect == '-') ++redirect, key = 'u'; if (stringEqual(redirect, "x")) i_puts(MSG_Junk); else printf("> %s\n", redirect); } else { if (*redirect == '-') ++redirect; if (stringEqual(redirect, "x")) redirect = NULL; } } /* display the next page of mail and get a command from the keyboard */ displine = 1; paging: if (!delflag) { /* show next page */ if (displine <= cw->dol) { for (j = 0; j < 20 && displine <= cw->dol; ++j, ++displine) { char *showline = (char *)fetchLine(displine, 1); k = pstLength((pst) showline); showline[--k] = 0; printf("%s\n", showline); nzFree(showline); } } } /* get key command from user */ key_command: if (delflag) goto writeMail; /* interactive prompt depends on whether there is more text or not */ printf("%c ", displine > cw->dol ? '?' : '*'); fflush(stdout); key = getLetter((isimap ? "q? nwWuUasd" : "q? nwud")); printf("\b\b\b"); fflush(stdout); switch (key) { case 'q': i_puts(MSG_Quit); exit(0); case 'n': i_puts(MSG_Next); goto afterinput; case 's': i_puts(MSG_Stop); goto afterinput; case 'd': i_puts(MSG_Delete); delflag = true; goto afterinput; case ' ': if (displine > cw->dol) i_puts(MSG_EndMessage); goto paging; case '?': i_puts(isimap ? MSG_ImapReadHelp : MSG_MailHelp); goto key_command; case 'a': key = 'w'; /* this will scan attachments */ scanat = true; case 'w': case 'W': case 'u': case 'U': break; default: i_puts(MSG_NYI); goto key_command; } /* switch */ /* At this point we're saving the mail somewhere. */ writeMail: if (!isimap || isupper(key)) delflag = true; atname = 0; if (!isimap) atname = redirect; if (scanat) goto attachOnly; saveMail: if (!atname) atname = getFileName(MSG_FileName, redirect, false, false); if (stringEqual(atname, "x")) goto afterinput; char exists = fileTypeByName(atname, false); int fsize; /* file size */ int fh = open(atname, O_WRONLY | O_TEXT | O_CREAT | O_APPEND, 0666); if (fh < 0) { i_printf(MSG_NoCreate, atname); goto saveMail; } if (exists) write(fh, "======================================================================\n", 71); if (key == 'u') { if (write(fh, mailstring, mailstring_l) < mailstring_l) { badsave: i_printf(MSG_NoWrite, atname); close(fh); goto saveMail; } close(fh); fsize = mailstring_l; } else { /* key = w, write the file - if pop then save the original unformatted */ if (!isimap && mailStash) { char *rmf; /* raw mail file */ int rmfh; /* file handle to same */ /* I want a fairly easy filename, in case I want to go look at the original. * Not a 30 character message ID that I am forced to cut&paste. * 4 or 5 digits would be nice. * So the filename looks like /home/foo/.Trash/rawmail/36921 * I pick the digits randomly. * Please don't accumulate 100,000 emails before you empty your trash. * It's good to have a cron job empty the trash early Sunday morning. */ k = strlen(mailStash); rmf = allocMem(k + 12); /* Try 20 times, then give up. */ for (j = 0; j < 20; ++j) { int rn = rand() % 100000; /* random number */ sprintf(rmf, "%s/%05d", mailStash, rn); if (fileTypeByName(rmf, false)) continue; /* dump the original mail into the file */ rmfh = open(rmf, O_WRONLY | O_TEXT | O_CREAT | O_APPEND, 0666); if (rmfh < 0) break; if (write(rmfh, mailstring, mailstring_l) < mailstring_l) { close(rmfh); unlink(rmf); break; } close(rmfh); /* written successfully, remember the stash number */ stashNumber = rn; break; } } fsize = 0; for (j = 1; j <= cw->dol; ++j) { char *showline = (char *)fetchLine(j, 1); int len = pstLength((pst) showline); if (write(fh, showline, len) < len) goto badsave; nzFree(showline); fsize += len; } /* loop over lines */ if (stashNumber >= 0) { char addstash[60]; sprintf(addstash, "\nUnformatted %05d\n", stashNumber); k = strlen(addstash); if (write(fh, addstash, k) < k) goto badsave; fsize += k; } close(fh); attachOnly: if (nattach) writeAttachments(lastMailInfo); else if (scanat) i_puts(MSG_NoAttachments); } /* unformat or format */ if (scanat) goto afterinput; /* print "mail saved" message */ i_printf(MSG_MailSaved, fsize); if (exists) i_printf(MSG_Appended); nl(); afterinput: nzFree(mailstring); mailstring = 0; nzFree(mailu8); mailu8 = 0; if (delflag) return 1; if (key == 's') return -1; return 0; } /* presentMail */
static iONode __translate( iOSPL inst, iONode node ) { iOSPLData data = Data(inst); iONode rsp = NULL; /* Switch command. */ if( StrOp.equals( NodeOp.getName( node ), wSwitch.name() ) ) { int addr = wSwitch.getaddr1( node ); int port = wSwitch.getport1( node ); Boolean state = StrOp.equals( wSwitch.getcmd( node ), wSwitch.straight ) ? 1:0; __setLED(inst, addr, port, state, True); } /* Output command */ else if( StrOp.equals( NodeOp.getName( node ), wOutput.name() ) ) { int addr = wOutput.getaddr( node ); int port = wOutput.getport( node ); Boolean state = StrOp.equals( wOutput.getcmd( node ), wOutput.on ); __setLED(inst, addr, port, state, True); } /* Signal command */ else if( StrOp.equals( NodeOp.getName( node ), wSignal.name() ) ) { int addr = wSignal.getaddr(node); int aspect = wSignal.getaspect(node); TraceOp.trc( name, TRCLEVEL_MONITOR, __LINE__, 9999, "signal addr=%d aspect=%d", addr, aspect ); char* cmd = allocMem( 32 ); StrOp.fmtb(cmd+1, "H%02XS%02X\r", addr, aspect); cmd[0] = StrOp.len(cmd+1); ThreadOp.post( data->writer, (obj)cmd ); } /* Program command */ else if( StrOp.equals( NodeOp.getName( node ), wProgram.name() ) ) { if( wProgram.getcmd( node ) == wProgram.set ) { if( wProgram.getcv(node) == 1 ) { char* cmd = allocMem( 32 ); TraceOp.trc( name, TRCLEVEL_MONITOR, __LINE__, 9999, "programming module address from 0x%02X to 0x%02X", wProgram.getaddr(node), wProgram.getvalue(node) ); StrOp.fmtb(cmd+1, "H%02XPaa55%02X\r", wProgram.getaddr(node), wProgram.getvalue(node)); cmd[0] = StrOp.len(cmd+1); ThreadOp.post( data->writer, (obj)cmd ); rsp = NodeOp.inst( wProgram.name(), NULL, ELEMENT_NODE ); if( data->iid != NULL ) wProgram.setiid( rsp, data->iid ); wProgram.setcmd( rsp, wProgram.datarsp ); wProgram.setcv( rsp, wProgram.getcv( node ) ); wProgram.setvalue( rsp, wProgram.getvalue( node ) ); } else { TraceOp.trc( name, TRCLEVEL_MONITOR, __LINE__, 9999, "unsupported cv %d", wProgram.getcv(node) ); rsp = NodeOp.inst( wProgram.name(), NULL, ELEMENT_NODE ); if( data->iid != NULL ) wProgram.setiid( rsp, data->iid ); wProgram.setcmd( rsp, wProgram.statusrsp ); wProgram.setcv( rsp, wProgram.getcv( node ) ); wProgram.setvalue( rsp, -1 ); } } else if( wProgram.getcmd( node ) == wProgram.nvset ) { if( wProgram.getcv(node) == 1 ) { TraceOp.trc( name, TRCLEVEL_MONITOR, __LINE__, 9999, "random range address from 0x%02X to 0x%02X with %d LEDs", wProgram.getval1(node), wProgram.getval2(node), wProgram.getval3(node) ); data->fromAddr = wProgram.getval1(node); data->toAddr = wProgram.getval2(node); data->nrLEDs = wProgram.getval3(node); wSPL.setfromaddr(data->splini, data->fromAddr ); wSPL.settoaddr(data->splini, data->toAddr ); wSPL.setnrleds(data->splini, data->nrLEDs ); } } } return rsp; }
/** * __parseREPLY -- returns a reply in replyline * * input : <REPLY queryObjects(10, name)> * output: <reply cmd="queryObjects" oid="10"> * * <reply rtype="0" cmd="get" oid="202" railcom="12" rc="0" msg="OK)>"> * <202 railcom="12, 64, 1"/> * </reply> * */ static void __parseREPLY( iONode node, const char* replyline ) { char replytype[ 32 ] = { '\0' }; char replycmd[ 64 ] = { '\0' }; int oid = 0; char *buffer = allocMem(StrOp.len(replyline)+1); char oidbuffer[ 64 ] = { '\0' }; char *bufptr; char tmp; /* Get the keyword and string remainder FARKLE -- sscanf sucks */ sscanf( replyline, "<%s %s", replytype, buffer ); TraceOp.trc( "ecosparser", TRCLEVEL_DEBUG, __LINE__, 9999, "__parseReply: replytype = [%s], buffer = [%s]", replytype, buffer ); int i = 0; int donecmd = 0; bufptr = buffer; while ( *bufptr ) { /* add the current char into the correct secondary buffer */ if ( !donecmd ) replycmd[ i++ ] = *bufptr++; else oidbuffer[ i++ ] = *bufptr++; /* Check for token end */ if ( *bufptr == '(' ) { /* command ends with '(', stop parsing command */ replycmd[ i ] = '\0'; bufptr++; donecmd = 1; i = 0; } else if ( *bufptr == ',' ) { /* ECoS id ends with ',', stop parsing oid */ oidbuffer[ i ] = '\0'; break; /* skip rest of line */ } } /* Get the oid from the oidbuffer FARKLE -- sscanf sucks */ sscanf( oidbuffer, "%d", &oid ); /* save the values into the node */ NodeOp.setStr( node, "cmd", replycmd ); NodeOp.setInt( node, "oid", oid ); /* TraceOp.trc( "ecosparser", TRCLEVEL_MONITOR, __LINE__, 9999, "header: type=%s cmd=%s oid=%d", replytype, replycmd, oid ); */ /* parse call parameters */ __parseCallParms(node, replyline); /* clean up */ freeMem(buffer); }