inline auto system_call(T&& scall) { static_assert( dummy<T>(), R"(type isn't callable without arguments.)"); decltype(scall()) retval = scall(); if (retval == -1) { throw std::system_error(errno, std::system_category()); } return retval; }
static def(String, BuildPath, String prefix, ListingItem *item, String ext) { String title = scall(Sanitize, item->title); String path = Storage_BuildPath(this->storage, this->providerId); String res = String_Format($("%/%%%.%"), path, prefix, (prefix.len > 0) ? $(" ") : $(""), title, ext); String_Destroy(&path); String_Destroy(&title); return res; }
static void set_epoch() { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); epoch_sec = ts.tv_sec; time(&server_start_unix_time); const char *server = background_mode? "/usr/local/bin/kiwid" : (BUILD_DIR "/kiwi.bin"); struct stat st; scall("stat kiwi server", stat(server, &st)); server_build_unix_time = st.st_mtime; init = true; }
// only done once per app run void sim_init() { // try and improve our performance a bit setpriority(PRIO_PROCESS, 0, -20); scall("mlockall", mlockall(MCL_CURRENT | MCL_FUTURE)); // check that new polarity scheme didn't break anything assert(WREG_O3_RST == WREG_O3_RST_GOOD); assert(WREG_O2_IDLE == WREG_O2_IDLE_GOOD); assert(WREG_O2_ENA == WREG_O2_ENA_GOOD); assert(WREG_O2_ARM == WREG_O2_ARM_GOOD); bus_init(); pru_start(); bus_pru_gpio_init(); if (!background_mode) { tty = open("/dev/tty", O_RDONLY | O_NONBLOCK); if (tty < 0) sys_panic("open tty"); } }
static const char* edata(const char *uri, size_t *size, char **free_buf) { const char* data = NULL; #ifdef EDATA_EMBED // the normal background daemon loads files from in-memory embedded data data = edata_embed(uri, size); #endif // some large, seldom-changed files are always loaded from memory if (!data) data = edata_always(uri, size); #ifdef EDATA_DEVEL // to speed edit-copy-compile-debug development, load the files from the local filesystem static bool init; if (!init) { scall("chdir web", chdir("web")); init = true; } // try as a local file if (!data) { int fd = open(uri, O_RDONLY); if (fd >= 0) { struct stat st; fstat(fd, &st); *size = st.st_size; data = (char *) wrx_malloc("file", *size); *free_buf = (char *) data; ssize_t rsize = read(fd, (void *) data, *size); assert(rsize == *size); close(fd); } } #endif return data; }
void ScriptMgr::LoadScripts() { if(HookInterface::getSingletonPtr() == NULL) new HookInterface; Log.Success("Server", "Loading External Script Libraries..."); std::string Path; std::string FileMask; Path = PREFIX; Path += '/'; #ifdef WIN32 /*Path = Config.MainConfig.GetStringDefault( "Script", "BinaryLocation", "script_bin" ); Path += "\\";*/ FileMask = ".dll"; #else #ifndef __APPLE__ FileMask = ".so"; #else FileMask = ".dylib"; #endif #endif Arcpro::FindFilesResult findres; std::vector< ScriptingEngine_dl > Engines; Arcpro::FindFiles(Path.c_str(), FileMask.c_str(), findres); uint32 count = 0; while(findres.HasNext()) { std::stringstream loadmessage; std::string fname = Path + findres.GetNext(); Arcpro::DynLib* dl = new Arcpro::DynLib(fname.c_str()); loadmessage << " " << dl->GetName() << " : "; if(!dl->Load()) { loadmessage << "ERROR: Cannot open library."; LOG_ERROR(loadmessage.str().c_str()); delete dl; continue; } else { exp_get_version vcall = reinterpret_cast< exp_get_version >(dl->GetAddressForSymbol("_exp_get_version")); exp_script_register rcall = reinterpret_cast< exp_script_register >(dl->GetAddressForSymbol("_exp_script_register")); exp_get_script_type scall = reinterpret_cast< exp_get_script_type >(dl->GetAddressForSymbol("_exp_get_script_type")); if((vcall == NULL) || (rcall == NULL) || (scall == NULL)) { loadmessage << "ERROR: Cannot find version functions."; LOG_ERROR(loadmessage.str().c_str()); delete dl; continue; } else { const char *version = vcall(); uint32 stype = scall(); if( strcmp( version, BUILD_HASH_STR ) != 0 ) { loadmessage << "ERROR: Version mismatch."; LOG_ERROR(loadmessage.str().c_str()); delete dl; continue; } else { loadmessage << ' ' << std::string( BUILD_HASH_STR ) << " : "; if((stype & SCRIPT_TYPE_SCRIPT_ENGINE) != 0) { ScriptingEngine_dl se; se.dl = dl; se.InitializeCall = rcall; se.Type = stype; Engines.push_back(se); loadmessage << "delayed load"; } else { rcall(this); dynamiclibs.push_back(dl); loadmessage << "loaded"; } LOG_BASIC(loadmessage.str().c_str()); count++; } } } } if(count == 0) { LOG_ERROR(" No external scripts found! Server will continue to function with limited functionality."); } else { Log.Success("Server", "Loaded %u external libraries.", count); Log.Success("Server", "Loading optional scripting engine(s)..."); for(std::vector< ScriptingEngine_dl >::iterator itr = Engines.begin(); itr != Engines.end(); ++itr) { itr->InitializeCall(this); dynamiclibs.push_back(itr->dl); } Log.Success("Server", "Done loading scripting engine(s)..."); } }
std::string Component::scall(HttpRequest& request) { tnt::QueryParams qparam; return scall(request, qparam); }
def(void, Get, String prefix, ListingItem *item, String url) { this->location.len = 0; HTTP_Client client; URL_Parts parts = URL_Parse(url); HTTP_Client_Init(&client, parts.host); HTTP_Client_Events events; events.onVersion = (HTTP_OnVersion) EmptyCallback(); events.onHeader = (HTTP_OnHeader) Callback(this, ref(OnHeader)); HTTP_Client_SetEvents(&client, events); HTTP_Client_Request(&client, HTTP_Client_CreateRequest( parts.host, parts.path)); Logger_Debug(this->logger, $("URL: %"), url); URL_Parts_Destroy(&parts); HTTP_Client_FetchResponse(&client); size_t cnt = 0; bool error = false; if (this->location.len > 0) { if (cnt > 3) { Logger_Error(this->logger, $("Redirection loop.")); goto out; } cnt++; Logger_Debug(this->logger, $("Redirecting...")); call(Get, prefix, item, this->location); goto out; } String full = call(BuildPath, prefix, item, scall(GetMediaExtension, parts.path)); Logger_Debug(this->logger, $("Destination: %"), full); File file; File_Open(&file, full, FileStatus_Create | FileStatus_Truncate | FileStatus_WriteOnly); String_Destroy(&full); BufferedStream output; BufferedStream_Init(&output, File_AsStream(&file)); BufferedStream_SetOutputBuffer(&output, 128 * 1024); u64 got = 0; s64 total = HTTP_Client_GetLength(&client); size_t prevPercent = 100; String buf = String_New(HTTP_Client_ReadChunkSize); Terminal_ProgressBar pbar; Terminal_ProgressBar_Init(&pbar, &term); while (HTTP_Client_Read(&client, &buf)) { got += buf.len; try { BufferedStream_Write(&output, buf.buf, buf.len); } clean catch(File, WritingFailed) { error = true; excBreak; } finally { } tryEnd; size_t percent = (size_t) ((float) got / (float) total * 100); if (prevPercent != percent) { float gotmb = (float) got / 1024 / 1024; float totalmb = (float) total / 1024 / 1024; String strGot = Float_ToString(gotmb, 0.01, '.'); String strTotal = Float_ToString(totalmb, 0.01, '.'); String msg = String_Format($("Received % MiB of % MiB"), strGot, strTotal); String_Destroy(&strTotal); String_Destroy(&strGot); Terminal_ProgressBar_Render(&pbar, percent, msg); String_Destroy(&msg); } prevPercent = percent; } Terminal_ProgressBar_Clear(&pbar); String_Destroy(&buf); if (error) { /* Don't flush when closing the file. */ BufferedStream_Reset(&output); } BufferedStream_Close(&output); BufferedStream_Destroy(&output); out: HTTP_Client_Destroy(&client); if (error) { throw(DownloadFailed); } }
void SystemManager::Init() { /* Loading system for win32 */ #ifdef WIN32 string search_path = "./Plugins/*.dll"; WIN32_FIND_DATA data; uint32 count = 0; HANDLE find_handle = FindFirstFile( search_path.c_str(), &data ); if(find_handle == INVALID_HANDLE_VALUE) WriteConsole("No external scripts found." ); else { do { string full_path = data.cFileName; HMODULE mod = LoadLibrary( full_path.c_str() ); if( mod == 0 ) printf("Loading %s failed, crc=0x%p\r\n", data.cFileName, reinterpret_cast< uint32* >( mod )); else { // find version import exp_get_version vcall = (exp_get_version)GetProcAddress(mod, "_exp_get_version"); exp_script_update ucall = (exp_script_update)GetProcAddress(mod, "_exp_script_update"); exp_script_register rcall = (exp_script_register)GetProcAddress(mod, "_exp_script_register"); exp_get_script_type scall = (exp_get_script_type)GetProcAddress(mod, "_exp_get_script_type"); if(vcall == 0 || rcall == 0 || scall == 0 || ucall == 0) { printf("Loading %s failed, version info not found\r\n", data.cFileName); FreeLibrary(mod); } else { uint32 version = vcall(); uint32 stype = scall(); uint32 versionhigh = SCRIPTLIB_HIPART(version), versionlow = SCRIPTLIB_LOPART(version); std::stringstream cmsg; cmsg << "Loading " << data.cFileName << ", crc:0x" << reinterpret_cast< uint32* >( mod ); cmsg << ", Version:" << versionhigh << " " << versionlow << " delayed loading."; ScriptDLLs se; se.Handle = mod; se.InitializeCall = rcall; se.UpdateCall = ucall; se.Type = stype; se.highrev = versionhigh; se.lowrev = versionlow; DLLScriptVector.push_back( se ); WriteConsole(cmsg.str()); ++count; } } }while(FindNextFile(find_handle, &data)); FindClose(find_handle); printf("Loading %u external libraries.\r\n", count); for(vector<ScriptDLLs>::iterator itr = DLLScriptVector.begin(); itr != DLLScriptVector.end(); itr++) (*itr).InitializeCall(this); } #else /* Loading system for *nix */ struct dirent ** list; int filecount = scandir(PREFIX "/lib/", &list, 0, 0); uint32 count = 0; if(!filecount || !list || filecount < 0) WriteConsole("No external scripts found."); else { char *ext; while(filecount--) { ext = strrchr(list[filecount]->d_name, '.'); #ifdef HAVE_DARWIN if (ext != NULL && strstr(list[filecount]->d_name, ".0.dylib") == NULL && !strcmp(ext, ".dylib")) { #else if (ext != NULL && !strcmp(ext, ".so")) { #endif string full_path = "../lib/" + string(list[filecount]->d_name); SCRIPT_MODULE mod = dlopen(full_path.c_str(), RTLD_NOW); printf(" %s : 0x%p : ", list[filecount]->d_name, mod); if(mod == 0) printf("error! [%s]\r\n", dlerror()); else { // find version import exp_get_version vcall = (exp_get_version)dlsym(mod, "_exp_get_version"); exp_script_update ucall = (exp_script_update)dlsym(mod, "_exp_script_update"); exp_script_register rcall = (exp_script_register)dlsym(mod, "_exp_script_register"); exp_get_script_type scall = (exp_get_script_type)dlsym(mod, "_exp_get_script_type"); if(vcall == 0 || rcall == 0 || scall == 0 || ucall == 0) { WriteConsole("version functions not found!"); dlclose(mod); } else { int32 version = vcall(); uint32 stype = scall(); uint32 versionhigh = SCRIPTLIB_HIPART(version), versionlow = SCRIPTLIB_LOPART(version); ScriptDLLs se; se.Handle = mod; se.InitializeCall = rcall; se.UpdateCall = ucall; se.Type = stype; se.highrev = versionhigh; se.lowrev = versionlow; DLLScriptVector.push_back( se ); printf("v%u.%u : loaded.\r\n", versionhigh, versionlow); rcall(this); ++count; } } } free(list[filecount]); } free(list); WriteConsole(""); printf("Loaded %u external libraries.", count); WriteConsole(""); WriteConsole("Loading optional scripting engines..."); for(vector<ScriptingEngine>::iterator itr = ScriptEngines.begin(); itr != ScriptEngines.end(); itr++) itr->InitializeCall(this); WriteConsole("Done loading script engines..."); } #endif } void SystemManager::WriteConsole(const char* message) { Console::Write(gcnew System::String(message)+"\r\n"); }
int main(int argc, char *argv[]) { u2_t *up; int i; char s[32]; // enable generation of core file in /tmp scall("core_pattern", system("echo /tmp/core-%e-%s-%u-%g-%p-%t > /proc/sys/kernel/core_pattern")); const struct rlimit unlim = { RLIM_INFINITY, RLIM_INFINITY }; scall("setrlimit", setrlimit(RLIMIT_CORE, &unlim)); for (i=1; i<argc; ) { if (strcmp(argv[i], "-bg")==0) { background_mode = TRUE; bg=1; } if (strcmp(argv[i], "-off")==0) do_off = 1; if (strcmp(argv[i], "-down")==0) down = 1; if (strcmp(argv[i], "+gps")==0) do_gps = 1; if (strcmp(argv[i], "-gps")==0) do_gps = 0; if (strcmp(argv[i], "+sdr")==0) do_sdr = 1; if (strcmp(argv[i], "-sdr")==0) do_sdr = 0; if (strcmp(argv[i], "+fft")==0) do_fft = 1; if (strcmp(argv[i], "-stats")==0 || strcmp(argv[i], "+stats")==0) { if (i+1 < argc && isdigit(argv[i+1][0])) { i++; print_stats = strtol(argv[i], 0, 0); } else { print_stats = 1; } } if (strcmp(argv[i], "-eeprom")==0) create_eeprom = true; if (strcmp(argv[i], "-cmap")==0) color_map = 1; if (strcmp(argv[i], "-sim")==0) wf_sim = 1; if (strcmp(argv[i], "-real")==0) wf_real = 1; if (strcmp(argv[i], "-time")==0) wf_time = 1; if (strcmp(argv[i], "-port")==0) { i++; alt_port = strtol(argv[i], 0, 0); } if (strcmp(argv[i], "-p")==0) { alt_port = 8074; } if (strcmp(argv[i], "-dump")==0 || strcmp(argv[i], "+dump")==0) { i++; ev_dump = strtol(argv[i], 0, 0); } if (strcmp(argv[i], "-flip")==0) wf_flip = 1; if (strcmp(argv[i], "-start")==0) wf_start = 1; if (strcmp(argv[i], "-mult")==0) wf_mult = 1; if (strcmp(argv[i], "-multgen")==0) wf_mult_gen = 1; if (strcmp(argv[i], "-wmax")==0) wf_max = 1; if (strcmp(argv[i], "-olap")==0) wf_olap = 1; if (strcmp(argv[i], "-meas")==0) meas = 1; // do_fft if (strcmp(argv[i], "-none")==0) unwrap = 0; if (strcmp(argv[i], "-norm")==0) unwrap = 1; if (strcmp(argv[i], "-rev")==0) unwrap = 2; if (strcmp(argv[i], "-qi")==0) rev_iq = 1; if (strcmp(argv[i], "-ineg")==0) ineg = 1; if (strcmp(argv[i], "-qneg")==0) qneg = 1; if (strcmp(argv[i], "-file")==0) fft_file = 1; if (strcmp(argv[i], "-fftsize")==0) { i++; fftsize = strtol(argv[i], 0, 0); } if (strcmp(argv[i], "-fftuse")==0) { i++; fftuse = strtol(argv[i], 0, 0); } if (strcmp(argv[i], "-np")==0) { i++; noisePwr = strtol(argv[i], 0, 0); } if (strcmp(argv[i], "-rcordic")==0) rx_cordic = 1; if (strcmp(argv[i], "-rcic")==0) rx_cic = 1; if (strcmp(argv[i], "-rcic2")==0) rx_cic2 = 1; if (strcmp(argv[i], "-rdump")==0) rx_dump = 1; if (strcmp(argv[i], "-wcordic")==0) wf_cordic = 1; if (strcmp(argv[i], "-wcic")==0) wf_cic = 1; if (strcmp(argv[i], "-clkg")==0) spi_clkg = 1; if (strcmp(argv[i], "-wspr")==0) { i++; wspr = strtol(argv[i], 0, 0); } if (strcmp(argv[i], "-avg")==0) { i++; navg = strtol(argv[i], 0, 0); } if (strcmp(argv[i], "-tone")==0) { i++; tone = strtol(argv[i], 0, 0); } if (strcmp(argv[i], "-slc")==0) { i++; do_slice = strtol(argv[i], 0, 0); } if (strcmp(argv[i], "-rx")==0) { i++; rx_num = strtol(argv[i], 0, 0); } if (strcmp(argv[i], "-wf")==0) { i++; wf_num = strtol(argv[i], 0, 0); } if (strcmp(argv[i], "-spispeed")==0) { i++; spi_speed = strtol(argv[i], 0, 0); } if (strcmp(argv[i], "-spi")==0) { i++; spi_delay = strtol(argv[i], 0, 0); } if (strcmp(argv[i], "-ch")==0) { i++; gps_chans = strtol(argv[i], 0, 0); } if (strcmp(argv[i], "-y")==0) { i++; rx_yield = strtol(argv[i], 0, 0); } if (strcmp(argv[i], "-p0")==0) { i++; p0 = strtol(argv[i], 0, 0); } if (strcmp(argv[i], "-p1")==0) { i++; p1 = strtol(argv[i], 0, 0); } if (strcmp(argv[i], "-p2")==0) { i++; p2 = strtol(argv[i], 0, 0); } i++; while (i<argc && ((argv[i][0] != '+') && (argv[i][0] != '-'))) { i++; } } lprintf("KiwiSDR v%d.%d\n", VERSION_MAJ, VERSION_MIN); lprintf("compiled: %s %s\n", __DATE__, __TIME__); cfg_reload(CALLED_FROM_MAIN); if (!alt_port) { FILE *fp = fopen("/root/.kiwi_down", "r"); if (fp != NULL) { fclose(fp); lprintf("down by lock file\n"); down = 1; } } TaskInit(); bool need_hardware = (do_gps || do_sdr) && !down; // called early, in case another server already running so we can detect the busy socket and bail web_server_init(WS_INIT_CREATE); if (need_hardware) { peri_init(); fpga_init(); //pru_start(); u2_t ctrl = CTRL_EEPROM_WP; ctrl_clr_set(0xffff, ctrl); if (do_off) { printf("ADC_CLOCK *OFF*\n"); xit(0); } #ifdef BUILD_PROTOTYPE if (!do_gps) // prevent interference to GPS by external ADC clock on prototype #endif { ctrl |= adc_clock_enable? CTRL_OSC_EN : CTRL_ADCLK_GEN; } ctrl_clr_set(0, ctrl); if (ctrl & (CTRL_OSC_EN | CTRL_ADCLK_GEN)) printf("ADC_CLOCK %.6f MHz, CTRL_OSC_EN=%d, CTRL_ADCLK_GEN=%d\n", adc_clock/MHz, (ctrl&CTRL_OSC_EN)?1:0, (ctrl&CTRL_ADCLK_GEN)?1:0); else printf("ADC_CLOCK *OFF*\n"); } if (do_fft) { printf("==== IQ %s\n", rev_iq? "reverse":"normal"); if (ineg) printf("==== I neg\n"); if (qneg) printf("==== Q neg\n"); printf("==== unwrap %s\n", (unwrap==0)? "none" : ((unwrap==1)? "normal":"reverse")); } rx_server_init(); web_server_init(WS_INIT_START); if (do_gps) { if (!GPS_CHANS) panic("no GPS_CHANS configured"); gps_main(argc, argv); } #if 0 static int tty; if (!background_mode) { tty = open("/dev/tty", O_RDONLY | O_NONBLOCK); if (tty < 0) sys_panic("open tty"); } #endif #if 0 static int tty; if (!background_mode) { tty = open("/dev/tty", O_RDONLY | O_NONBLOCK); if (tty < 0) sys_panic("open tty"); } #endif static u64_t stats_deadline = timer_us64() + 1000000; static u64_t secs; while (TRUE) { if (!need_hardware) { usleep(10000); // pause so we don't hog the machine NextTask("main usleep"); continue; } #if 0 if (!background_mode && (now - last_input) >= 1000) { #define N_IBUF 32 char ib[N_IBUF+1]; int n = read(tty, ib, N_IBUF); printf("tty %d\n", n); if (n >= 1) { ib[n] = 0; webserver_collect_print_stats(1); } last_input = now; } #endif if ((secs % STATS_INTERVAL_SECS) == 0) { if (do_sdr) { webserver_collect_print_stats(!do_gps); if (!do_gps) nbuf_stat(); } TaskCheckStacks(); } NextTask("main stats"); if (!do_gps && print_stats) { if (!background_mode) { lprintf("ECPU %4.1f%% cmds %d/%d malloc %d\n", ecpu_use(), ecpu_cmds, ecpu_tcmds, kiwi_malloc_stat()); ecpu_cmds = ecpu_tcmds = 0; TaskDump(); printf("\n"); } } u64_t now_us = timer_us64(); s64_t diff = stats_deadline - now_us; if (diff > 0) TaskSleep(diff); stats_deadline += 1000000; secs++; } }