unsigned int anak_kirim( unsigned int identifikasi, FILE *pberkas, RSA *rsapub, RSA *rsapriv, struct KIRIMBERKAS *kirim, struct INFOALAMAT *infoalamat, int ukuberkas_panjang ){ char pesan[CHUNK_MESSAGE_SIZE]; char pecahan[ENCRYPTED_CONTAINER_SIZE]; size_t panjang_pesan=0; // Perilaku. int status=0;; int maksimal_coba=aturan.tries; int ulang_tunggu=aturan.waitretry; int urut_tunggu=aturan.waitqueue; unsigned int kelompok_kirim=kirim->kelompok_kirim; char *nama_berkas=kirim->berkas; // Identifikasi. bool identifikasi_awal=true; unsigned int identifikasi_sebelumnya=kirim->identifikasi_sebelumnya; // Pengepala Pecahan. int paritas=0; int panji=0; int status_gerbang=0; int status_peladen=0; // Tujuan. char *hostname=kirim->hostname; char *portno=kirim->portno; // Berurutan kirim. kirim->urut_kali++; // Membersihkan isi. memset(pesan, 0, CHUNK_MESSAGE_SIZE); memset(pecahan, 0, MAX_CHUNK_SIZE); // Bila identifikasi // lebih dari MAX_CHUNK_ID, // maka identifikasi adalah NOL. if(identifikasi>MAX_CHUNK_ID){ DEBUG1(_("Telah melebihi maksimal identifikasi %1$i."), MAX_CHUNK_ID); DEBUG1(_("Nilai identifikasi adalah %1$i."), identifikasi); // Ke NOL. identifikasi=0; DEBUG1(_("Mengubah identifikasi ke nilai 0."), 0); // Keluar. DEBUG1(_("Tidak melanjutkan pengiriman."), 0); return identifikasi; }; // Apakah pertama. if(kirim->paksa_panji!=UNDEFINED_FLAG){ // Memaksa panji. panji=kirim->paksa_panji; kirim->paksa_panji=UNDEFINED_FLAG; // Pesan. DEBUG1(_("Memaksa panji '%1$s'."),arti_panji(panji)); // Langsung berhenti bila panji STOP. if(panji==STOP_FLAG){ // Mengirim panji STOP // dan keluar dari perulangan. DEBUG1(_("Menghentikan pengulangan pengiriman."), 0); kirim->do_kirim=false; }; }else if(identifikasi==0){ // Panji. panji=START_FLAG; // Memastikan nama berkas ada. if(!strlen(nama_berkas)){ // Kesalahan. FAIL(_("Gagal memperoleh nama berkas."), 0); exit(EXIT_FAILURE_MEMORY); }; // Pecahan pertama adalah // pecahan dengan informasi berkas. memcpy(pesan, buat_pesan_start( pesan, CHUNK_MESSAGE_SIZE, kirim->berkas_identifikasi, nama_berkas, kirim->ukuran_berkas ), CHUNK_MESSAGE_SIZE); // Apakah hampir akhir. }else if(identifikasi==MAX_CHUNK_ID){ // Panji. DEBUG1(_("Mengirim panji '%1$s'."),_("Henti")); panji=STOP_FLAG; /* }else if (kirim->ukuran_kirim>kirim->ukuran_berkas){ // Panji STOP. DEBUG1(_("Mengirim panji '%1$s'."), _("Henti")); panji=STOP_FLAG; // Hentikan perulangan. // Keluar dari perulangan. DEBUG1(_("Menghentikan pengulangan pengiriman."), 0); kirim->do_kirim=false; */ }else{ // Panji. panji=INTRANSFER_FLAG; // Mendapatkan posisi berkas. long int penunjuk_berkas=0 +((long)(kelompok_kirim-1)*(MAX_CHUNK_ID-1)*CHUNK_MESSAGE_SIZE) +((long)identifikasi-1)*(long)CHUNK_MESSAGE_SIZE; // Bila mendekati dan pecahan transfer terakhir, // maka penunjuk merupakan // panjang berkas dikurangi CHUNK_MESSAGE_SIZE. // Aktifkan dengan aturan.shifteof=true. int panjang_geser_akhir=0; size_t panjang_baca=CHUNK_MESSAGE_SIZE; if ( aturan.shifteof && kirim->ukuran_kirim + (double)CHUNK_MESSAGE_SIZE >= kirim->ukuran_berkas && kirim->ukuran_berkas - kirim->ukuran_kirim <= (double)CHUNK_MESSAGE_SIZE ){ // Pesan. DEBUG3(_("Merupakan pecahan akhir."), 0); // Jumlah geser. panjang_geser_akhir=(int)0 +((double)CHUNK_MESSAGE_SIZE -(kirim->ukuran_berkas-kirim->ukuran_kirim)); // Mengubah penunjuk berkas. penunjuk_berkas=kirim->ukuran_berkas-CHUNK_MESSAGE_SIZE; // Panjang baca. panjang_baca=CHUNK_MESSAGE_SIZE; }else{ // Jumlah geser. panjang_geser_akhir=0; // Panjang baca. panjang_baca=CHUNK_MESSAGE_SIZE; }; // Menggeser penunjuk berkas. status=fseek(pberkas, penunjuk_berkas, SEEK_SET); // Memeriksa posisi. if(status<0){ FAIL( _("Gagal memindah posisi penunjuk berkas '%1$s': %2$s (%3$i)."), nama_berkas, strerror(errno), errno ); exit(EXIT_FAILURE_IO); }else{ long posisi_sekarang=ftell(pberkas); if(posisi_sekarang<0){ FAIL( _("Gagal mendapatkan posisi penunjuk berkas '%1$s': %2$s (%3$i)."), nama_berkas, strerror(errno), errno ); exit(EXIT_FAILURE_IO); }else if(posisi_sekarang!=penunjuk_berkas){ FAIL( _("Posisi penunjuk berkas '%1$s' (%2$li) tidak sesuai. Diharapkan: %2$li."), nama_berkas, posisi_sekarang, errno ); exit(EXIT_FAILURE_IO); }else{ // Berhasil. if(kelompok_kirim>1){ DEBUG3( _("Mulai membaca di bita %1$i sebesar %2$lu bita untuk pesan %3$i kelompok %4$i."), penunjuk_berkas, (long unsigned int) panjang_baca, identifikasi, kelompok_kirim ); }else{ DEBUG3( _("Mulai membaca di bita %1$i sebesar %2$lu bita untuk pesan %3$i."), penunjuk_berkas, (long unsigned int) panjang_baca, identifikasi ); }; }; }; // Baca berkas untuk pesan. panjang_pesan=fread(pesan, 1, CHUNK_MESSAGE_SIZE, pberkas); // Menambah bita terkirim. if(identifikasi_awal || identifikasi!=identifikasi_sebelumnya){ // Menambah. identifikasi_awal=false; // kirim->ukuran_kirim+=(double)panjang_pesan; identifikasi_sebelumnya=identifikasi; kirim->identifikasi_sebelumnya=identifikasi; }; // Menggeser. if( panjang_geser_akhir>0 && panjang_geser_akhir <= CHUNK_MESSAGE_SIZE ){ // Membuat sementara. char pesan_tmp[CHUNK_MESSAGE_SIZE+1]; memset(pesan_tmp, 0, CHUNK_MESSAGE_SIZE+1); // Mengeser. panjang_pesan=CHUNK_MESSAGE_SIZE-panjang_geser_akhir; memmove(pesan_tmp+0, pesan+panjang_geser_akhir, panjang_pesan); // Mengembalikan. memset(pesan, 0, CHUNK_MESSAGE_SIZE); memcpy(pesan, pesan_tmp, panjang_pesan); // Membersihkan. memset(pesan_tmp, 0, CHUNK_MESSAGE_SIZE+1); // Pesan. DEBUG3( _("Menggeser pesan sebanyak %1$i bita."), panjang_geser_akhir ); DEBUG3( _("Mulai dibaca di bita %1$i sebesar %2$lu bita"), penunjuk_berkas+panjang_geser_akhir, panjang_pesan ); }; // Bila telah selesai. // Kecuali bila aturan.transferedcheck=true // maka penghentian melihat bita terterima Peladen // bukan bila berkas kosong. Berguna bila merupakan // sambungan paralel sehingga saat pecahan melebihi ukuran, // tidak langsung menghentikan. if ( (!panjang_pesan && !aturan.transferedcheck) || (!panjang_pesan && ( kirim->ukuran_kirim > kirim->ukuran_berkas+(CHUNK_MESSAGE_SIZE*10) ) ) ){ DEBUG3(_("Panjang pesan akhir adalah %1$i bita"), panjang_pesan); if(feof(pberkas)!=0){ // Selesai kirim. char penyangga_feof[ukuberkas_panjang]; INFO( _("Berkas '%1$s' dengan ukuran %2$s (%3$.0lf bita) telah selesai dikirim."), nama_berkas, readable_fs(kirim->ukuran_berkas, penyangga_feof), kirim->ukuran_berkas ); memset(penyangga_feof, 0, ukuberkas_panjang); clearerr(pberkas); }else if(ferror(pberkas)!=0){ // Kesalahan. FAIL( _("Gagal membaca berkas '%1$s': %2$s (%3$i)."), nama_berkas, strerror(errno), errno ); clearerr(pberkas); exit(EXIT_FAILURE_IO); }else{ // Kesalahan. WARN( _("Kesalahan berkas yang tidak diketahui: %1$s (%2$i)."), strerror(errno), errno ); }; // Pesan. DEBUG1(_("Mengirim panji '%1$s'."),_("Henti")); panji=STOP_FLAG; // Mengirim panji STOP // dan keluar dari perulangan. DEBUG1(_("Menghentikan pengulangan pengiriman."), 0); kirim->do_kirim=false; }else{ // Pesan. DEBUG3(_("Panjang pesan adalah %1$i bita"), panjang_pesan); }; }; // Bangun pesan. memcpy(pecahan, buat_pesan( pecahan, identifikasi, &paritas, pesan ), MAX_CHUNK_SIZE); // Bangun pengepala. DEBUG2(_("Panji %1$s."), arti_panji(panji)); memcpy(pecahan, buat_pengepala( pecahan, identifikasi, panji, paritas, status_gerbang, status_peladen ), MAX_CHUNK_SIZE); // Pesan. if(kelompok_kirim>1){ DEBUG1( _("Mengirim pesan %1$i kelompok %2$i."), identifikasi, kelompok_kirim); }else{ DEBUG1( _("Mengirim pesan %1$i."), identifikasi); }; // ============= Enkripsi ======= int panjang_pecahan; // Enkripsi. if(!aturan.rawtransfer){ // Pesan mentah. DEBUG5(_("Pesan mentah dikirim"), pecahan, 0, MAX_CHUNK_SIZE); // Penyandian. unsigned char pesan_ency[MAX_CHUNK_SIZE+1]; memcpy(pesan_ency, pecahan, MAX_CHUNK_SIZE); unsigned char tujuan_ency[ENCRYPTED_CONTAINER_SIZE+1]; panjang_pecahan=rsa_encrypt( pesan_ency, MAX_CHUNK_SIZE+1, tujuan_ency, rsapub, aturan.rsa_padding ); // Bersihkan. memset(pesan_ency, 0, MAX_CHUNK_SIZE); // Pesan mentah. DEBUG5( _("Pesan mentah dikirim tersandikan"), tujuan_ency, 0, MAX_CHUNK_SIZE ); // Salin. memcpy(pecahan, tujuan_ency, panjang_pecahan); }else{ panjang_pecahan=MAX_CHUNK_SIZE; }; // ============ /Enkripsi ======= // Kirim. int panjang_diterima; char *kirim_data=kirimdata( pecahan, panjang_pecahan, hostname, portno, infoalamat, &panjang_diterima ); // Bila kosong. if(kirim_data == NULL){ // Pesan kesalahan. DEBUG1(_("Kegagalan %1$s."), _("Soket")); // Keluar. exit(EXIT_FAILURE_SOCKET); }; // Menyalin isi. memcpy(pecahan, kirim_data, ENCRYPTED_CONTAINER_SIZE); // Pesan mentah. DEBUG4(_("Panjang pesan mentah diterima: %1$i"), panjang_pecahan); DEBUG5(_("Pesan mentah diterima"), pecahan, 0, panjang_pecahan); // ============= Dekripsi ======= if(!aturan.rawtransfer){ // Pemecah sandi. unsigned char pesan_deco[ENCRYPTED_CONTAINER_SIZE+1]; memcpy(pesan_deco, pecahan, ENCRYPTED_CONTAINER_SIZE); unsigned char tujuan_deco[MAX_CHUNK_SIZE+1]; panjang_pecahan=rsa_decrypt( pesan_deco, panjang_diterima, tujuan_deco, rsapriv, aturan.rsa_padding ); // Periksa. // print_unsigned_array(tujuan_deco, 100); // Bersihkan. memset(pesan_deco, 0, MAX_CHUNK_SIZE); // Pesan mentah. DEBUG4( _("Panjang pesan mentah diterima terpecahkan: %1$i"), panjang_pecahan ); DEBUG5( _("Pesan mentah diterima terpecahkan"), tujuan_deco, 0, panjang_pecahan ); // Salin. memcpy(pecahan, tujuan_deco, MAX_CHUNK_SIZE); }; // ============ /Dekripsi ======= // Mendapatkan pesan. DEBUG4(_("Membersihkan penampung pesan."), 0); memset(pesan, 0, CHUNK_MESSAGE_SIZE); DEBUG4(_("Menyalin pesan."), 0); memcpy(pesan, ambil_pesan(pecahan), CHUNK_MESSAGE_SIZE); DEBUG4(_("Selesai menyalin pesan."), 0); // Periksa. // print_unsigned_array(tujuan_deco, 100); // Mendapatkan pengepala. // Respons. int r_versi; int r_panji; int r_paritas; int r_status_gerbang; int r_status_peladen; unsigned int r_identifikasi; DEBUG4(_("Mendapatkan pengepala."), 0); ambil_pengepala( pecahan, &r_versi, &r_identifikasi, &r_panji, &r_paritas, &r_status_gerbang, &r_status_peladen ); DEBUG4(_("Selesai mendapatkan pengepala."), 0); // Mendapatkan informasi peladen. char* r_berkas_id; char* berkas_ukuran_str; char* berkas_diterima_str; char* unix_time_str; // Alikasi memori. r_berkas_id=malloc( sizeof(r_berkas_id)* (CHUNK_MESSAGE_SIZE/2)); berkas_ukuran_str=malloc( sizeof(berkas_ukuran_str)* (CHUNK_MESSAGE_SIZE/2)); berkas_diterima_str=malloc( sizeof(berkas_diterima_str)* (CHUNK_MESSAGE_SIZE/2)); unix_time_str=malloc( sizeof(unix_time_str)* (CHUNK_MESSAGE_SIZE/2)); // Membersihkan isi. memset(r_berkas_id, 0, sizeof(r_berkas_id)* (CHUNK_MESSAGE_SIZE/2)); memset(berkas_ukuran_str, 0, sizeof(berkas_ukuran_str)* (CHUNK_MESSAGE_SIZE/2)); memset(berkas_diterima_str, 0, sizeof(berkas_diterima_str)* (CHUNK_MESSAGE_SIZE/2)); memset(unix_time_str, 0, sizeof(unix_time_str)* (CHUNK_MESSAGE_SIZE/2)); // Ambil informasi. DEBUG4(_("Mendapatkan informasi peladen."), 0); DEBUG5(_("Pesan"), pesan, 0, CHUNK_MESSAGE_SIZE); status=ambil_pesan_peladen( pesan, CHUNK_MESSAGE_SIZE, &r_berkas_id, &berkas_ukuran_str, &berkas_diterima_str, &unix_time_str ); DEBUG4(_("Selesai mendapatkan informasi peladen."), 0); // Ubah nilai. double r_berkas_ukuran=0; double r_berkas_diterima=0; double r_unixtime=0; if(status>0){ // Tidak menerima. DEBUG1( _("Tidak memahami Peladen di pecahan %1$i (Status %2$i)."), r_identifikasi, status ); }else{ // Ubah nilai. r_berkas_ukuran=strtod(berkas_ukuran_str, NULL); r_berkas_diterima=strtod(berkas_diterima_str, NULL); r_unixtime=strtod(unix_time_str, NULL); }; // Balasan DEBUG2(_("Balasan: Versi: %1$i."), r_versi); DEBUG2(_("Balasan: Identifikasi: %1$i."), r_identifikasi); DEBUG2(_("Balasan: Panji: %1$s."), arti_panji(r_panji)); DEBUG2(_("Balasan: Paritas: %1$i."), r_paritas); DEBUG2(_("Balasan: Status Gerbang: %1$s."), arti_status(r_status_gerbang)); DEBUG2(_("Balasan: Status Peladen: %1$s."), arti_status(r_status_peladen)); DEBUG2(_("Balasan: Identifikasi berkas: %1$s."), r_berkas_id); DEBUG2(_("Balasan: Ukuran berkas: %1$.0f bita."), r_berkas_ukuran); DEBUG2(_("Balasan: Berkas diterima: %1$.0f bita."), r_berkas_diterima) DEBUG2(_("Balasan: Waktu Peladen: %1$.06f."), r_unixtime); DEBUG1( _("Perbedaan waktu Peladen: %1$.06f detik."), infokancil.unixtime-r_unixtime ); // Menyimpan. if(r_berkas_diterima<=0){ DEBUG2( _("Berkas terterima berukuran %1$.0f bita."), r_berkas_diterima ); }else{ kirim->ukuran_kirim=r_berkas_diterima; }; // Bila berkas yang diterima // telah sama atau lebih besar dari ukuran. if( aturan.transferedcheck && r_berkas_diterima>=kirim->ukuran_berkas ){ // Pesan. if( (r_berkas_diterima-kirim->ukuran_berkas) > (double)CHUNK_MESSAGE_SIZE * (aturan.parallel) ){ WARN( _("Peladen telah menerima berkas melebihi %1$.0f bita."), r_berkas_diterima-kirim->ukuran_berkas ); }else if(r_berkas_diterima>kirim->ukuran_berkas){ DEBUG1( _("Peladen telah menerima berkas melebihi %1$.0f bita."), r_berkas_diterima-kirim->ukuran_berkas ); }else{ DEBUG1(_("Peladen telah menerima keseluruhan berkas."), 0); }; // Ubah nilai. kirim->ukuran_kirim=r_berkas_diterima; kirim->paksa_panji=STOP_FLAG; // Keluar. return identifikasi; }; // Memeriksa hasil. // Bila status gerbang atau peladen adalah NOL. if(!r_status_gerbang || !r_status_peladen){ // Memeriksa apakah // telah terlalu banyak melakukan percobaan. if(kirim->coba>maksimal_coba){ FAIL( _("Telah melakukan percobaan sebanyak %1$i kali. Berhenti."), maksimal_coba ); exit(EXIT_FAILURE); }else if(!r_status_gerbang && !r_status_peladen){ WARN( _("Gagal mengirim ke %1$s dan %2$s."), _("Gerbang"),_("Peladen") ); }else if(!r_status_peladen){ WARN(_("Gagal mengirim ke %1$s."),_("Peladen")); }else{ WARN(_("Gagal mengirim ke %1$s."),_("Gerbang")); }; // Panji Taksah. if(r_panji==INVALID_FLAG){ // Pesan. NOTICE(_("Panji Taksah ditemukan."), 0); NOTICE( _("Menunggu %1$i detik untuk mengirim ulang."), ulang_tunggu ); sleep(ulang_tunggu); }else if(r_panji==START_FLAG){ // Mengunlang pengiriman // informasi berkas. int tunggu=ulang_tunggu; NOTICE(_("Meminta pengiriman ulang informasi berkas."), 0); NOTICE(_("Menunggu %1$i detik untuk mengirim ulang."), tunggu); sleep(tunggu); // Mengatur ulang ukuran berkas terkirim. kirim->ukuran_kirim=0; }else if(r_panji==INTRANSFER_FLAG){ // Meminta pengiriman ulang // berkas berdasarkan identifikasi. NOTICE( _("Meminta pengiriman ulang pecahan identifikasi '%1$i'."), r_identifikasi ); // Mengatur ulang ukuran berkas terkirim // sesuai dengan ukuran peladen. kirim->ukuran_kirim=r_berkas_diterima; }; // Mengirim ulang. NOTICE( _("Percobaan ke-%1$i. Mengulangi pengiriman pecahan %2$i."), kirim->coba, r_identifikasi ); identifikasi=r_identifikasi; // Menambah // percobaan pengiriman. kirim->coba++; }else{ /* // Bila ukuran terterima Peladen // lebih besar dari pada terketahui Klien. if(r_berkas_diterima> kirim->ukuran_kirim){ // Pesan. DEBUG2( _("Peladen telah menerima berkas melebihi %1$.0f bita dari yang terkirim."), r_berkas_diterima-(kirim->ukuran_berkas) ); // Ubah isi. kirim->ukuran_kirim=r_berkas_diterima; }; */ // Berhasil. DEBUG2(_("Berhasil mengirim ke Gerbang dan Peladen."), 0); // Menambahkan. identifikasi++; DEBUG2(_("Menambah identifikasi menjadi %1$i."), identifikasi); // Bila belum selesai. if(kirim->ukuran_kirim<=kirim->ukuran_berkas){ // Bila lebih dari spesifikasi, // mengulangi dari NOL. if(identifikasi>MAX_CHUNK_ID){ // Pesan. WARN( _("Telah melebihi maksimal identifikasi %1$i."), MAX_CHUNK_ID ); DEBUG1(_("Nilai identifikasi adalah %1$i."), identifikasi); // Perkembangan. tampil_info_progres_berkas( PROGRES_KIRIM, kirim->berkas, kirim->ukuran_kirim, kirim->ukuran_berkas, ukuberkas_panjang ); // Menambah kelompok. kelompok_kirim++; kirim->kelompok_kirim=kelompok_kirim; // Pesan. DEBUG1( _("Menunggu %1$i detik untuk melanjutkan."), urut_tunggu ); DEBUG1( _("Kelompok pecahan selanjutnya adalah '%1$i'."), kelompok_kirim ); // Tunggu. sleep(urut_tunggu); // Mengulangi identifikasi. identifikasi=0; }; }else{ // DEBUG1(_("Menghentikan pengulangan pengiriman."), 0); // kirim->do_kirim=false; }; kirim->coba=1; }; /* // Bila lebih dari maksimal kali kirim, // menunggu sebanyak waktu untuk mengirim ulang. if(kirim->urut_kali>=urut_maksimal && !urut_jangan_tunggu){ // Pesan. WARN( _("Telah mengirim berurutan sebanyak %1$i kali."), kirim->urut_kali ); // Perkembangan. tampil_info_progres_berkas( PROGRES_KIRIM, kirim->berkas, kirim->ukuran_kirim, kirim->ukuran_berkas, ukuberkas_panjang ); // Pesan. NOTICE(_("Menunggu %1$i detik untuk mengirim ulang."), urut_tunggu); sleep(urut_tunggu); kirim->urut_kali=0; }; */ // Memastikan nilai kelompok benar. kirim->kelompok_kirim=kelompok_kirim; // Mengembalikan nilai identifikasi. return identifikasi; // kirim->identifikasi=identifikasi; // Mengembalikan data. // kirim->berkas=berkas; // if(identifikasi>3) // kirim->do_kirim=false; }
int start (int argc,char ** argv) { #else int main(int argc, char *argv[]) { #endif NODE *exec_list = NIL; NODE *cl_tail = NIL; int argc2; char **argv2; #ifdef SYMANTEC_C extern void (*openproc)(void); extern void __open_std(void); openproc = &__open_std; #endif #ifdef mac init_mac_memory(); #endif bottom_stack = &exec_list; /*GC*/ #ifndef HAVE_WX #ifdef x_window x_window_init(argc, argv); #endif #endif (void)addseg(); term_init(); init(); math_init(); #ifdef ibm signal(SIGINT, SIG_IGN); #if defined(__RZTC__) && !defined(WIN32) /* sowings */ _controlc_handler = do_ctrl_c; controlc_open(); #endif #else /* !ibm */ signal(SIGINT, logo_stop); #endif /* ibm */ #ifdef mac signal(SIGQUIT, SIG_IGN); #else /* !mac */ //signal(SIGQUIT, logo_pause); #endif /* SIGQUITs never happen on the IBM */ if (argc < 2) { #ifndef WIN32 if (1 || isatty(1)) // fix this. for interactive from menu bar. #endif { #ifdef HAVE_WX extern char *SVN; #endif char version[20]; lcleartext(NIL); #ifdef HAVE_WX strcpy(version,"6.0"); strcat(version,SVN); #else strcpy(version,"5.6"); #endif ndprintf(stdout, message_texts[WELCOME_TO], version); new_line(stdout); } } #ifdef HAVE_WX setvalnode__caseobj(LogoVersion, make_floatnode(6.0)); #else setvalnode__caseobj(LogoVersion, make_floatnode(5.6)); #endif setflag__caseobj(LogoVersion, VAL_BURIED); argv2 = argv; argc2 = argc; if (!strcmp(*argv+strlen(*argv)-4, "logo")) { argv++; while (--argc > 0 && strcmp(*argv, "-") && NOT_THROWING) { argv++; } } argv++; while (--argc > 0) { if (command_line == NIL) cl_tail = command_line = cons(make_static_strnode(*argv++), NIL); else { setcdr(cl_tail, cons(make_static_strnode(*argv++), NIL)); cl_tail = cdr(cl_tail); } } setvalnode__caseobj(CommandLine, command_line); silent_load(Startuplg, logolib); silent_load(Startup, NULL); /* load startup.lg */ if (!strcmp(*argv2+strlen(*argv2)-4, "logo")) { argv2++; while (--argc2 > 0 && strcmp(*argv2, "-") && NOT_THROWING) { silent_load(NIL,*argv2++); } } for (;;) { if (NOT_THROWING) { check_reserve_tank(); current_line = reader(stdin,"? "); #ifdef __RZTC__ (void)feof(stdin); if (!in_graphics_mode) printf(" \b"); fflush(stdout); #endif #ifndef WIN32 if (feof(stdin) && !isatty(0)) lbye(NIL); #endif #ifdef __RZTC__ if (feof(stdin)) clearerr(stdin); #endif if (NOT_THROWING) { exec_list = parser(current_line, TRUE); if (exec_list != NIL) eval_driver(exec_list); } } #ifdef HAVE_WX if (wx_leave_mainloop) { break; } #endif if (stopping_flag == THROWING) { if (isName(throw_node, Name_error)) { err_print(NULL); } else if (isName(throw_node, Name_system)) break; else if (!isName(throw_node, Name_toplevel)) { err_logo(NO_CATCH_TAG, throw_node); err_print(NULL); } stopping_flag = RUN; } if (stopping_flag == STOP || stopping_flag == OUTPUT) { /* ndprintf(stdout, "%t\n", message_texts[CANT_STOP]); */ stopping_flag = RUN; } } //prepare_to_exit(TRUE); exit(0); return 0; }
/** void LogCollectorStart() v0.4 * Handle file management. */ void LogCollectorStart() { int i = 0, r = 0; int max_file = 0; int f_check = 0; time_t curr_time = 0; char keepalive[1024]; /* To check for inode changes */ struct stat tmp_stat; #ifndef WIN32 int int_error = 0; struct timeval fp_timeout; #else /* Checking if we are on vista. */ checkVista(); /* Reading vista descriptions. */ if(isVista) { win_read_vista_sec(); } #endif debug1("%s: DEBUG: Entering LogCollectorStart().", ARGV0); /* Initializing each file and structure */ for(i = 0;;i++) { if(logff[i].file == NULL) break; /* Removing duplicate entries. */ for(r = 0; r < i; r++) { if(logff[r].file && strcmp(logff[i].file, logff[r].file) == 0) { merror("%s: WARN: Duplicated log file given: '%s'.", ARGV0, logff[i].file); logff[i].file = NULL; logff[i].command = NULL; logff[i].fp = NULL; break; } } if(logff[i].file == NULL) { /* do nothing, duplicated entry. */ } else if(strcmp(logff[i].logformat,"eventlog") == 0) { #ifdef WIN32 verbose(READING_EVTLOG, ARGV0, logff[i].file); win_startel(logff[i].file); #endif logff[i].file = NULL; logff[i].command = NULL; logff[i].fp = NULL; } else if(strcmp(logff[i].logformat, "eventchannel") == 0) { #ifdef WIN32 #ifdef EVENTCHANNEL_SUPPORT verbose(READING_EVTLOG, ARGV0, logff[i].file); win_start_event_channel(logff[i].file, logff[i].future, logff[i].query); #else merror("%s: WARN: eventchannel not available on this version of OSSEC", ARGV0); #endif #endif logff[i].file = NULL; logff[i].command = NULL; logff[i].fp = NULL; } else if(strcmp(logff[i].logformat, "command") == 0) { logff[i].file = NULL; logff[i].fp = NULL; logff[i].size = 0; if(logff[i].command) { logff[i].read = read_command; verbose("%s: INFO: Monitoring output of command(%d): %s", ARGV0, logff[i].ign, logff[i].command); if(!logff[i].alias) { os_strdup(logff[i].command, logff[i].alias); } } else { merror("%s: ERROR: Missing command argument. Ignoring it.", ARGV0); } } else if(strcmp(logff[i].logformat, "full_command") == 0) { logff[i].file = NULL; logff[i].fp = NULL; logff[i].size = 0; if(logff[i].command) { logff[i].read = read_fullcommand; verbose("%s: INFO: Monitoring full output of command(%d): %s", ARGV0, logff[i].ign, logff[i].command); if(!logff[i].alias) os_strdup(logff[i].command, logff[i].alias); } else { merror("%s: ERROR: Missing command argument. Ignoring it.", ARGV0); } } else { logff[i].command = NULL; /* Initializing the files */ if(logff[i].ffile) { /* Day must be zero for all files to be initialized */ _cday = 0; if(update_fname(i)) { handle_file(i, 1, 1); } else { ErrorExit(PARSE_ERROR, ARGV0, logff[i].ffile); } } else { handle_file(i, 1, 1); } verbose(READING_FILE, ARGV0, logff[i].file); /* Getting the log type */ if(strcmp("snort-full", logff[i].logformat) == 0) { logff[i].read = read_snortfull; } #ifndef WIN32 if(strcmp("ossecalert", logff[i].logformat) == 0) { logff[i].read = read_ossecalert; } #endif else if(strcmp("nmapg", logff[i].logformat) == 0) { logff[i].read = read_nmapg; } else if(strcmp("mysql_log", logff[i].logformat) == 0) { logff[i].read = read_mysql_log; } else if(strcmp("mssql_log", logff[i].logformat) == 0) { logff[i].read = read_mssql_log; } else if(strcmp("postgresql_log", logff[i].logformat) == 0) { logff[i].read = read_postgresql_log; } else if(strcmp("djb-multilog", logff[i].logformat) == 0) { if(!init_djbmultilog(i)) { merror(INV_MULTILOG, ARGV0, logff[i].file); if(logff[i].fp) { fclose(logff[i].fp); logff[i].fp = NULL; } logff[i].file = NULL; } logff[i].read = read_djbmultilog; } else if(logff[i].logformat[0] >= '0' && logff[i].logformat[0] <= '9') { logff[i].read = read_multiline; } else { logff[i].read = read_syslog; } /* More tweaks for Windows. For some reason IIS places * some wierd characters at the end of the files and getc * always returns 0 (even after clearerr). */ #ifdef WIN32 if(logff[i].fp) { logff[i].read(i, &r, 1); } #endif } if(logff[i].alias) { int ii = 0; while(logff[i].alias[ii] != '\0') { if(logff[i].alias[ii] == ':') { logff[i].alias[ii] = '\\'; } ii++; } } } /* Start up message */ verbose(STARTUP_MSG, ARGV0, (int)getpid()); max_file = i -1; /* Cannot be zero */ if(max_file < 0) { max_file = 0; } /* Daemon loop */ while(1) { #ifndef WIN32 fp_timeout.tv_sec = loop_timeout; fp_timeout.tv_usec = 0; /* Waiting for the select timeout */ if ((r = select(0, NULL, NULL, NULL, &fp_timeout)) < 0) { merror(SELECT_ERROR, ARGV0, errno, strerror(errno)); int_error++; if(int_error >= 5) { ErrorExit(SYSTEM_ERROR, ARGV0); } continue; } #else /* Windows don't like select that way */ sleep(loop_timeout + 2); /* Check for messages in the event viewer */ win_readel(); #endif f_check++; /* Checking which file is available */ for(i = 0; i <= max_file; i++) { if(!logff[i].fp) { /* Run the command. */ if(logff[i].command && (f_check %2)) { curr_time = time(0); if((curr_time - logff[i].size) >= logff[i].ign) { logff[i].size = curr_time; logff[i].read(i, &r, 0); } } continue; } /* Windows with IIS logs is very strange. * For some reason it always returns 0 (not EOF) * the fgetc. To solve this problem, we always * pass it to the function pointer directly. */ #ifndef WIN32 /* We check for the end of file. If is returns EOF, * we don't attempt to read it. */ if((r = fgetc(logff[i].fp)) == EOF) { clearerr(logff[i].fp); continue; } /* If it is not EOF, we need to return the read character */ ungetc(r, logff[i].fp); #endif /* Finally, send to the function pointer to read it */ logff[i].read(i, &r, 0); /* Checking for error */ if(!ferror(logff[i].fp)) { /* Clearing EOF */ clearerr(logff[i].fp); /* Parsing error */ if(r != 0) { logff[i].ign++; } } /* If ferror is set */ else { merror(FREAD_ERROR, ARGV0, logff[i].file, errno, strerror(errno)); #ifndef WIN32 if(fseek(logff[i].fp, 0, SEEK_END) < 0) #else if(1) #endif { #ifndef WIN32 merror(FSEEK_ERROR, ARGV0, logff[i].file, errno, strerror(errno)); #endif /* Closing the file */ if(logff[i].fp) { fclose(logff[i].fp); #ifdef WIN32 CloseHandle(logff[i].h); #endif } logff[i].fp = NULL; /* Trying to open it again */ if(handle_file(i, 1, 1) != 0) { logff[i].ign++; continue; } #ifdef WIN32 logff[i].read(i, &r, 1); #endif } /* Increase the error count */ logff[i].ign++; clearerr(logff[i].fp); } } /* Only check bellow if check > VCHECK_FILES */ if(f_check <= VCHECK_FILES) continue; /* Send keep alive message */ rand_keepalive_str(keepalive, 700); SendMSG(logr_queue, keepalive, "ossec-keepalive", LOCALFILE_MQ); /* Zeroing f_check */ f_check = 0; /* Checking if any file has been renamed/removed */ for(i = 0; i <= max_file; i++) { /* These are the windows logs or ignored files */ if(!logff[i].file) continue; /* Files with date -- check for day change */ if(logff[i].ffile) { if(update_fname(i)) { if(logff[i].fp) { fclose(logff[i].fp); #ifdef WIN32 CloseHandle(logff[i].h); #endif } logff[i].fp = NULL; handle_file(i, 0, 1); continue; } /* Variable file name */ else if(!logff[i].fp) { handle_file(i, 0, 0); continue; } } /* Check for file change -- if the file is open already */ if(logff[i].fp) { #ifndef WIN32 if(fstat(fileno(logff[i].fp), &tmp_stat) == -1) { fclose(logff[i].fp); logff[i].fp = NULL; merror(FSTAT_ERROR, ARGV0, logff[i].file, errno, strerror(errno)); } #else BY_HANDLE_FILE_INFORMATION lpFileInformation; HANDLE h1; h1 = CreateFile(logff[i].file, GENERIC_READ, FILE_SHARE_DELETE|FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if(h1 == INVALID_HANDLE_VALUE) { fclose(logff[i].fp); CloseHandle(logff[i].h); logff[i].fp = NULL; merror(FILE_ERROR, ARGV0, logff[i].file); } else if(GetFileInformationByHandle(h1, &lpFileInformation) == 0) { fclose(logff[i].fp); CloseHandle(logff[i].h); CloseHandle(h1); logff[i].fp = NULL; merror(FILE_ERROR, ARGV0, logff[i].file);; } #endif #ifdef WIN32 else if(logff[i].fd != (lpFileInformation.nFileIndexLow + lpFileInformation.nFileIndexHigh)) #else else if(logff[i].fd != tmp_stat.st_ino) #endif { char msg_alert[512 +1]; snprintf(msg_alert, 512, "ossec: File rotated (inode " "changed): '%s'.", logff[i].file); /* Send message about log rotated */ SendMSG(logr_queue, msg_alert, "ossec-logcollector", LOCALFILE_MQ); debug1("%s: DEBUG: File inode changed. %s", ARGV0, logff[i].file); fclose(logff[i].fp); #ifdef WIN32 CloseHandle(logff[i].h); CloseHandle(h1); #endif logff[i].fp = NULL; handle_file(i, 0, 1); continue; } #ifdef WIN32 else if(logff[i].size > (lpFileInformation.nFileSizeHigh + lpFileInformation.nFileSizeLow)) #else else if(logff[i].size > tmp_stat.st_size) #endif { char msg_alert[512 +1]; snprintf(msg_alert, 512, "ossec: File size reduced " "(inode remained): '%s'.", logff[i].file); /* Send message about log rotated */ SendMSG(logr_queue, msg_alert, "ossec-logcollector", LOCALFILE_MQ); debug1("%s: DEBUG: File size reduced. %s", ARGV0, logff[i].file); /* Fixing size so we don't alert more than once */ logff[i].size = tmp_stat.st_size; /* Getting new file. */ fclose(logff[i].fp); #ifdef WIN32 CloseHandle(logff[i].h); CloseHandle(h1); #endif logff[i].fp = NULL; handle_file(i, 1, 1); } #ifdef WIN32 else { CloseHandle(h1); } #endif } /* Too many errors for the file */ if(logff[i].ign > open_file_attempts) { /* 999 Maximum ignore */ if(logff[i].ign == 999) { continue; } merror(LOGC_FILE_ERROR, ARGV0, logff[i].file); if(logff[i].fp) { fclose(logff[i].fp); #ifdef WIN32 CloseHandle(logff[i].h); #endif } logff[i].fp = NULL; /* If the file has a variable date, ignore it for * today only. */ if(!logff[i].ffile) { /* Variable log files should always be attempted * to be open... */ //logff[i].file = NULL; } logff[i].ign = 999; continue; } /* File not opened */ if(!logff[i].fp) { if(logff[i].ign >= 999) continue; else { /* Try for a few times to open the file */ if(handle_file(i, 1, 1) < 0) { logff[i].ign++; } continue; } } } } }
void log_record( int eventtype, /* I */ int objclass, /* I */ const char *objname, /* I */ const char *text) /* I */ { int tryagain = 2; time_t now; pid_t thr_id = -1; struct tm *ptm; struct tm tmpPtm; int rc = 0; FILE *savlog; char *start = NULL, *end = NULL; size_t nchars; int eventclass = 0; char time_formatted_str[64]; thr_id = syscall(SYS_gettid); pthread_mutex_lock(log_mutex); if (log_opened < 1) { pthread_mutex_unlock(log_mutex); return; } now = time((time_t *)0); /* get time for message */ ptm = localtime_r(&now,&tmpPtm); /* Do we need to switch the log? */ if (log_auto_switch && (ptm->tm_yday != log_open_day)) { log_close(1); log_open(NULL, log_directory); if (log_opened < 1) { pthread_mutex_unlock(log_mutex); return; } } time_formatted_str[0] = 0; log_get_set_eventclass(&eventclass, GETV); if (eventclass == PBS_EVENTCLASS_TRQAUTHD) { log_format_trq_timestamp(time_formatted_str, sizeof(time_formatted_str)); } /* * Looking for the newline characters and splitting the output message * on them. Sequence "\r\n" is mapped to the single newline. */ start = (char *)text; while (1) { for (end = start; *end != '\n' && *end != '\r' && *end != '\0'; end++) ; nchars = end - start; if (*end == '\r' && *(end + 1) == '\n') end++; while (tryagain) { if (eventclass != PBS_EVENTCLASS_TRQAUTHD) { rc = fprintf(logfile, "%02d/%02d/%04d %02d:%02d:%02d;%04x;%10.10s.%d;%s;%s;%s%.*s\n", ptm->tm_mon + 1, ptm->tm_mday, ptm->tm_year + 1900, ptm->tm_hour, ptm->tm_min, ptm->tm_sec, (eventtype & ~PBSEVENT_FORCE), msg_daemonname, thr_id, class_names[objclass], objname, (text == start ? "" : "[continued]"), (int)nchars, start); } else { rc = fprintf(logfile, "%s %s%.*s\n", time_formatted_str, (text == start ? "" : "[continued]"), (int)nchars, start); } if ((rc < 0) && (errno == EPIPE) && (tryagain == 2)) { /* the log file descriptor has been changed--it now points to a socket! * reopen log and leave the previous file descriptor alone--do not close it */ log_opened = 0; log_open(NULL, log_directory); tryagain--; } else { tryagain = 0; } } if (rc < 0) break; if (*end == '\0') break; start = end + 1; } /* END while (1) */ fflush(logfile); if (rc < 0) { rc = errno; clearerr(logfile); savlog = logfile; logfile = fopen("/dev/console", "w"); /* we need to add this check to make sure the disk isn't full so we don't segfault * if we can't open this then we're going to have a nice surprise failure */ if (logfile != NULL) { pthread_mutex_unlock(log_mutex); log_err(rc, __func__, "PBS cannot write to its log"); fclose(logfile); pthread_mutex_lock(log_mutex); } logfile = savlog; } pthread_mutex_unlock(log_mutex); return; } /* END log_record() */
/***************************************************************************** * config_LoadConfigFile: loads the configuration file. ***************************************************************************** * This function is called to load the config options stored in the config * file. *****************************************************************************/ int config_LoadConfigFile( vlc_object_t *p_this ) { FILE *file; file = config_OpenConfigFile (p_this); if (file == NULL) return VLC_EGENERIC; /* Look for UTF-8 Byte Order Mark */ char * (*convert) (const char *) = strdupnull; char bom[3]; if ((fread (bom, 1, 3, file) != 3) || memcmp (bom, "\xEF\xBB\xBF", 3)) { convert = FromLocaleDup; rewind (file); /* no BOM, rewind */ } char *line = NULL; size_t bufsize; ssize_t linelen; /* Ensure consistent number formatting... */ locale_t loc = newlocale (LC_NUMERIC_MASK, "C", NULL); locale_t baseloc = uselocale (loc); vlc_rwlock_wrlock (&config_lock); while ((linelen = getline (&line, &bufsize, file)) != -1) { line[linelen - 1] = '\0'; /* trim newline */ /* Ignore comments, section and empty lines */ if (memchr ("#[", line[0], 3) != NULL) continue; /* look for option name */ const char *psz_option_name = line; char *ptr = strchr (line, '='); if (ptr == NULL) continue; /* syntax error */ *ptr = '\0'; module_config_t *item = config_FindConfig (p_this, psz_option_name); if (item == NULL) continue; const char *psz_option_value = ptr + 1; switch (item->i_type) { case CONFIG_ITEM_BOOL: case CONFIG_ITEM_INTEGER: { int64_t l; errno = 0; l = strtoi (psz_option_value); if ((l > item->max.i) || (l < item->min.i)) errno = ERANGE; if (errno) msg_Warn (p_this, "Integer value (%s) for %s: %m", psz_option_value, psz_option_name); else item->value.i = l; break; } case CONFIG_ITEM_FLOAT: if (!*psz_option_value) break; /* ignore empty option */ item->value.f = (float)atof (psz_option_value); break; default: free ((char *)item->value.psz); item->value.psz = convert (psz_option_value); break; } } vlc_rwlock_unlock (&config_lock); free (line); if (ferror (file)) { msg_Err (p_this, "error reading configuration: %m"); clearerr (file); } fclose (file); if (loc != (locale_t)0) { uselocale (baseloc); freelocale (loc); } return 0; }
/* Function to display source in the source window. */ enum tui_status tui_set_source_content (struct symtab *s, int line_no, int noerror) { enum tui_status ret = TUI_FAILURE; if (s != (struct symtab *) NULL && s->filename != (char *) NULL) { FILE *stream; int i, desc, c, line_width, nlines; char *src_line = 0; if ((ret = tui_alloc_source_buffer (TUI_SRC_WIN)) == TUI_SUCCESS) { line_width = TUI_SRC_WIN->generic.width - 1; /* Take hilite (window border) into account, when calculating the number of lines. */ nlines = (line_no + (TUI_SRC_WIN->generic.height - 2)) - line_no; desc = open_source_file (s); if (desc < 0) { if (!noerror) { char *name = alloca (strlen (s->filename) + 100); sprintf (name, "%s:%d", s->filename, line_no); print_sys_errmsg (name, errno); } ret = TUI_FAILURE; } else { if (s->line_charpos == 0) find_source_lines (s, desc); if (line_no < 1 || line_no > s->nlines) { close (desc); printf_unfiltered ( "Line number %d out of range; %s has %d lines.\n", line_no, s->filename, s->nlines); } else if (lseek (desc, s->line_charpos[line_no - 1], 0) < 0) { close (desc); perror_with_name (s->filename); } else { int offset, cur_line_no, cur_line, cur_len, threshold; struct tui_gen_win_info *locator = tui_locator_win_info_ptr (); struct tui_source_info *src = &TUI_SRC_WIN->detail.source_info; if (TUI_SRC_WIN->generic.title) xfree (TUI_SRC_WIN->generic.title); TUI_SRC_WIN->generic.title = xstrdup (s->filename); if (src->filename) xfree (src->filename); src->filename = xstrdup (s->filename); /* Determine the threshold for the length of the line and the offset to start the display. */ offset = src->horizontal_offset; threshold = (line_width - 1) + offset; stream = fdopen (desc, FOPEN_RT); clearerr (stream); cur_line = 0; src->gdbarch = get_objfile_arch (s->objfile); src->start_line_or_addr.loa = LOA_LINE; cur_line_no = src->start_line_or_addr.u.line_no = line_no; if (offset > 0) src_line = (char *) xmalloc ( (threshold + 1) * sizeof (char)); while (cur_line < nlines) { struct tui_win_element *element = (struct tui_win_element *) TUI_SRC_WIN->generic.content[cur_line]; /* Get the first character in the line. */ c = fgetc (stream); if (offset == 0) src_line = ((struct tui_win_element *) TUI_SRC_WIN->generic.content[ cur_line])->which_element.source.line; /* Init the line with the line number. */ sprintf (src_line, "%-6d", cur_line_no); cur_len = strlen (src_line); i = cur_len - ((cur_len / tui_default_tab_len ()) * tui_default_tab_len ()); while (i < tui_default_tab_len ()) { src_line[cur_len] = ' '; i++; cur_len++; } src_line[cur_len] = (char) 0; /* Set whether element is the execution point and whether there is a break point on it. */ element->which_element.source.line_or_addr.loa = LOA_LINE; element->which_element.source.line_or_addr.u.line_no = cur_line_no; element->which_element.source.is_exec_point = (strcmp (((struct tui_win_element *) locator->content[0])->which_element.locator.file_name, s->filename) == 0 && cur_line_no == ((struct tui_win_element *) locator->content[0])->which_element.locator.line_no); if (c != EOF) { i = strlen (src_line) - 1; do { if ((c != '\n') && (c != '\r') && (++i < threshold)) { if (c < 040 && c != '\t') { src_line[i++] = '^'; src_line[i] = c + 0100; } else if (c == 0177) { src_line[i++] = '^'; src_line[i] = '?'; } else { /* Store the charcter in the line buffer. If it is a tab, then translate to the correct number of chars so we don't overwrite our buffer. */ if (c == '\t') { int j, max_tab_len = tui_default_tab_len (); for (j = i - ((i / max_tab_len) * max_tab_len); j < max_tab_len && i < threshold; i++, j++) src_line[i] = ' '; i--; } else src_line[i] = c; } src_line[i + 1] = 0; } else { /* If we have not reached EOL, then eat chars until we do. */ while (c != EOF && c != '\n' && c != '\r') c = fgetc (stream); /* Handle non-'\n' end-of-line. */ if (c == '\r' && (c = fgetc (stream)) != '\n' && c != EOF) { ungetc (c, stream); c = '\r'; } } } while (c != EOF && c != '\n' && c != '\r' && i < threshold && (c = fgetc (stream))); } /* Now copy the line taking the offset into account. */ if (strlen (src_line) > offset) strcpy (((struct tui_win_element *) TUI_SRC_WIN->generic.content[ cur_line])->which_element.source.line, &src_line[offset]); else ((struct tui_win_element *) TUI_SRC_WIN->generic.content[ cur_line])->which_element.source.line[0] = (char) 0; cur_line++; cur_line_no++; } if (offset > 0) xfree (src_line); fclose (stream); TUI_SRC_WIN->generic.content_size = nlines; ret = TUI_SUCCESS; } } } } return ret; }
int main(int argc, char **argv) { if ((argc == 2 && strcmp(argv[1], "-v") == 0) || (argc == 2 && strcmp(argv[1], "--version") == 0)) { char *versionStrP; fprintf(stderr, "tesseract %s\n", tesseract::TessBaseAPI::Version()); versionStrP = getLeptonicaVersion(); fprintf(stderr, " %s\n", versionStrP); lept_free(versionStrP); versionStrP = getImagelibVersions(); fprintf(stderr, " %s\n", versionStrP); lept_free(versionStrP); #ifdef USE_OPENCL cl_platform_id platform; cl_uint num_platforms; cl_device_id devices[2]; cl_uint num_devices; char info[256]; int i; fprintf(stderr, " OpenCL info:\n"); clGetPlatformIDs(1, &platform, &num_platforms); fprintf(stderr, " Found %d platforms.\n", num_platforms); clGetPlatformInfo(platform, CL_PLATFORM_NAME, 256, info, 0); fprintf(stderr, " Platform name: %s.\n", info); clGetPlatformInfo(platform, CL_PLATFORM_VERSION, 256, info, 0); fprintf(stderr, " Version: %s.\n", info); clGetDeviceIDs(platform, CL_DEVICE_TYPE_ALL, 2, devices, &num_devices); fprintf(stderr, " Found %d devices.\n", num_devices); for (i = 0; i < num_devices; ++i) { clGetDeviceInfo(devices[i], CL_DEVICE_NAME, 256, info, 0); fprintf(stderr, " Device %d name: %s.\n", i+1, info); } #endif exit(0); } // Make the order of args a bit more forgiving than it used to be. const char* lang = "eng"; const char* image = NULL; const char* output = NULL; const char* datapath = NULL; bool noocr = false; bool list_langs = false; bool print_parameters = false; tesseract::PageSegMode pagesegmode = tesseract::PSM_AUTO; int arg = 1; while (arg < argc && (output == NULL || argv[arg][0] == '-')) { if (strcmp(argv[arg], "-l") == 0 && arg + 1 < argc) { lang = argv[arg + 1]; ++arg; } else if (strcmp(argv[arg], "--tessdata-dir") == 0 && arg + 1 < argc) { datapath = argv[arg + 1]; ++arg; } else if (strcmp(argv[arg], "--list-langs") == 0) { noocr = true; list_langs = true; } else if (strcmp(argv[arg], "-psm") == 0 && arg + 1 < argc) { pagesegmode = static_cast<tesseract::PageSegMode>(atoi(argv[arg + 1])); ++arg; } else if (strcmp(argv[arg], "--print-parameters") == 0) { noocr = true; print_parameters = true; } else if (strcmp(argv[arg], "-c") == 0 && arg + 1 < argc) { // handled properly after api init ++arg; } else if (image == NULL) { image = argv[arg]; } else if (output == NULL) { output = argv[arg]; } ++arg; } if (argc == 2 && strcmp(argv[1], "--list-langs") == 0) { list_langs = true; noocr = true; } if (output == NULL && noocr == false) { fprintf(stderr, "Usage:\n %s imagename|stdin outputbase|stdout " "[options...] [configfile...]\n\n", argv[0]); fprintf(stderr, "OCR options:\n"); fprintf(stderr, " --tessdata-dir /path\tspecify location of tessdata" " path\n"); fprintf(stderr, " -l lang[+lang]\tspecify language(s) used for OCR\n"); fprintf(stderr, " -c configvar=value\tset value for control parameter.\n" "\t\t\tMultiple -c arguments are allowed.\n"); fprintf(stderr, " -psm pagesegmode\tspecify page segmentation mode.\n"); fprintf(stderr, "These options must occur before any configfile.\n\n"); fprintf(stderr, "pagesegmode values are:\n" " 0 = Orientation and script detection (OSD) only.\n" " 1 = Automatic page segmentation with OSD.\n" " 2 = Automatic page segmentation, but no OSD, or OCR\n" " 3 = Fully automatic page segmentation, but no OSD. (Default)\n" " 4 = Assume a single column of text of variable sizes.\n" " 5 = Assume a single uniform block of vertically aligned text.\n" " 6 = Assume a single uniform block of text.\n" " 7 = Treat the image as a single text line.\n" " 8 = Treat the image as a single word.\n" " 9 = Treat the image as a single word in a circle.\n" " 10 = Treat the image as a single character.\n\n"); fprintf(stderr, "Single options:\n"); fprintf(stderr, " -v --version: version info\n"); fprintf(stderr, " --list-langs: list available languages for tesseract " "engine. Can be used with --tessdata-dir.\n"); fprintf(stderr, " --print-parameters: print tesseract parameters to the " "stdout.\n"); exit(1); } if (output != NULL && strcmp(output, "-") && strcmp(output, "stdout")) { tprintf("Tesseract Open Source OCR Engine v%s with Leptonica\n", tesseract::TessBaseAPI::Version()); } PERF_COUNT_START("Tesseract:main") tesseract::TessBaseAPI api; api.SetOutputName(output); int rc = api.Init(datapath, lang, tesseract::OEM_DEFAULT, &(argv[arg]), argc - arg, NULL, NULL, false); if (rc) { fprintf(stderr, "Could not initialize tesseract.\n"); exit(1); } char opt1[255], opt2[255]; for (arg = 0; arg < argc; arg++) { if (strcmp(argv[arg], "-c") == 0 && arg + 1 < argc) { strncpy(opt1, argv[arg + 1], 255); *(strchr(opt1, '=')) = 0; strncpy(opt2, strchr(argv[arg + 1], '=') + 1, 255); opt2[254] = 0; ++arg; if (!api.SetVariable(opt1, opt2)) { fprintf(stderr, "Could not set option: %s=%s\n", opt1, opt2); } } } if (list_langs) { GenericVector<STRING> languages; api.GetAvailableLanguagesAsVector(&languages); fprintf(stderr, "List of available languages (%d):\n", languages.size()); for (int index = 0; index < languages.size(); ++index) { STRING& string = languages[index]; fprintf(stderr, "%s\n", string.string()); } api.End(); exit(0); } if (print_parameters) { FILE* fout = stdout; fprintf(stdout, "Tesseract parameters:\n"); api.PrintVariables(fout); api.End(); exit(0); } // We have 2 possible sources of pagesegmode: a config file and // the command line. For backwards compatability reasons, the // default in tesseract is tesseract::PSM_SINGLE_BLOCK, but the // default for this program is tesseract::PSM_AUTO. We will let // the config file take priority, so the command-line default // can take priority over the tesseract default, so we use the // value from the command line only if the retrieved mode // is still tesseract::PSM_SINGLE_BLOCK, indicating no change // in any config file. Therefore the only way to force // tesseract::PSM_SINGLE_BLOCK is from the command line. // It would be simpler if we could set the value before Init, // but that doesn't work. if (api.GetPageSegMode() == tesseract::PSM_SINGLE_BLOCK) api.SetPageSegMode(pagesegmode); bool stdInput = !strcmp(image, "stdin") || !strcmp(image, "-"); Pix* pixs = NULL; if (stdInput) { char byt; GenericVector<l_uint8> ch_data; std::istream file(std::cin.rdbuf()); #ifdef WIN32 if (_setmode(_fileno(stdin), _O_BINARY) == -1) tprintf("ERROR: cin to binary: %s", strerror(errno)); #endif // WIN32 while (file.get(byt)) { ch_data.push_back(byt); } std::cin.ignore(std::cin.rdbuf()->in_avail() + 1); pixs = pixReadMem(&ch_data[0], ch_data.size()); } if (pagesegmode == tesseract::PSM_AUTO_ONLY || pagesegmode == tesseract::PSM_OSD_ONLY) { int ret_val = 0; if (!pixs) pixs = pixRead(image); if (!pixs) { fprintf(stderr, "Cannot open input file: %s\n", image); exit(2); } api.SetImage(pixs); if (pagesegmode == tesseract::PSM_OSD_ONLY) { OSResults osr; if (api.DetectOS(&osr)) { int orient = osr.best_result.orientation_id; int script_id = osr.get_best_script(orient); float orient_oco = osr.best_result.oconfidence; float orient_sco = osr.best_result.sconfidence; tprintf("Orientation: %d\nOrientation in degrees: %d\n" \ "Orientation confidence: %.2f\n" \ "Script: %d\nScript confidence: %.2f\n", orient, OrientationIdToValue(orient), orient_oco, script_id, orient_sco); } else { ret_val = 1; } } else { tesseract::Orientation orientation; tesseract::WritingDirection direction; tesseract::TextlineOrder order; float deskew_angle; tesseract::PageIterator* it = api.AnalyseLayout(); if (it) { it->Orientation(&orientation, &direction, &order, &deskew_angle); tprintf("Orientation: %d\nWritingDirection: %d\nTextlineOrder: %d\n" \ "Deskew angle: %.4f\n", orientation, direction, order, deskew_angle); } else { ret_val = 1; } delete it; } pixDestroy(&pixs); exit(ret_val); } tesseract::TessResultRenderer* renderer = NULL; bool b; api.GetBoolVariable("tessedit_create_hocr", &b); if (b && renderer == NULL) renderer = new tesseract::TessHOcrRenderer(); api.GetBoolVariable("tessedit_create_pdf", &b); if (b && renderer == NULL) renderer = new tesseract::TessPDFRenderer(api.GetDatapath()); api.GetBoolVariable("tessedit_create_boxfile", &b); if (b && renderer == NULL) renderer = new tesseract::TessBoxTextRenderer(); if (renderer == NULL) renderer = new tesseract::TessTextRenderer(); if (pixs) { api.ProcessPage(pixs, 0, NULL, NULL, 0, renderer); pixDestroy(&pixs); } else { FILE* fin = fopen(image, "rb"); if (fin == NULL) { fprintf(stderr, "Cannot open input file: %s\n", image); exit(2); } fclose(fin); if (!api.ProcessPages(image, NULL, 0, renderer)) { fprintf(stderr, "Error during processing.\n"); exit(1); } } FILE* fout = stdout; if (strcmp(output, "-") && strcmp(output, "stdout")) { STRING outfile = STRING(output) + STRING(".") + STRING(renderer->file_extension()); fout = fopen(outfile.string(), "wb"); if (fout == NULL) { fprintf(stderr, "Cannot create output file %s\n", outfile.string()); exit(1); } } const char* data; inT32 data_len; if (renderer->GetOutput(&data, &data_len)) { fwrite(data, 1, data_len, fout); if (fout != stdout) fclose(fout); else clearerr(fout); } PERF_COUNT_END return 0; // Normal exit }
static void file_stdio_fclearerr(ALLEGRO_FILE *f) { USERDATA *userdata = get_userdata(f); clearerr(userdata->fp); }
int main(int argc, char **argv) { int c; int updates = 0; char *usage = "Usage: %s [-v] [-f prom-device]" " [variable[=value] ...]"; eplist_t *elist; benv_des_t *bd; char *file = NULL; setpname(argv[0]); while ((c = getopt(argc, argv, "f:Itv")) != -1) switch (c) { case 'v': verbose++; break; case 'f': file = optarg; break; case 't': test++; break; default: exit(_error(NO_PERROR, usage, argv[0])); } (void) uname(&uts_buf); bd = new_bd(); init_benv(bd, file); map_benv(bd); if (bd->len) { parse_benv(bd); unmap_benv(bd); } elist = bd->elist; if (optind >= argc) { print_vars(elist); return (0); } else while (optind < argc) { /* * If "-" specified, read variables from stdin; * otherwise, process each argument as a variable * print or set request. */ if (strcmp(argv[optind], "-") == 0) { char *line; while ((line = get_line()) != NULL) updates += proc_var(line, elist); clearerr(stdin); } else updates += proc_var(argv[optind], elist); optind++; } /* * don't write benv if we are processing delayed writes since * it is likely that the delayed writes changes bootenv.rc anyway... */ if (updates) write_benv(bd); close_kbenv(); return (0); }
static batch_job_id_t batch_job_condor_wait (struct batch_queue * q, struct batch_job_info * info_out, time_t stoptime) { static FILE *logfile = 0; if(!logfile) { logfile = fopen(q->logfile, "r"); if(!logfile) { debug(D_NOTICE, "couldn't open logfile %s: %s\n", q->logfile, strerror(errno)); return -1; } } while(1) { /* Note: clearerr is necessary to clear any cached end-of-file condition, otherwise some implementations of fgets (i.e. darwin) will read to end of file once and then never look for any more data. */ clearerr(logfile); char line[BATCH_JOB_LINE_MAX]; while(fgets(line, sizeof(line), logfile)) { int type, proc, subproc; batch_job_id_t jobid; time_t current; struct tm tm; struct batch_job_info *info; int logcode, exitcode; if(sscanf(line, "%d (%" SCNbjid ".%d.%d) %d/%d %d:%d:%d", &type, &jobid, &proc, &subproc, &tm.tm_mon, &tm.tm_mday, &tm.tm_hour, &tm.tm_min, &tm.tm_sec) == 9) { tm.tm_year = 2008 - 1900; tm.tm_isdst = 0; current = mktime(&tm); info = itable_lookup(q->job_table, jobid); if(!info) { info = malloc(sizeof(*info)); memset(info, 0, sizeof(*info)); itable_insert(q->job_table, jobid, info); } debug(D_BATCH, "line: %s", line); if(type == 0) { info->submitted = current; } else if(type == 1) { info->started = current; debug(D_BATCH, "job %" PRIbjid " running now", jobid); } else if(type == 9) { itable_remove(q->job_table, jobid); info->finished = current; info->exited_normally = 0; info->exit_signal = SIGKILL; debug(D_BATCH, "job %" PRIbjid " was removed", jobid); memcpy(info_out, info, sizeof(*info)); free(info); return jobid; } else if(type == 5) { itable_remove(q->job_table, jobid); info->finished = current; fgets(line, sizeof(line), logfile); if(sscanf(line, " (%d) Normal termination (return value %d)", &logcode, &exitcode) == 2) { debug(D_BATCH, "job %" PRIbjid " completed normally with status %d.", jobid, exitcode); info->exited_normally = 1; info->exit_code = exitcode; } else if(sscanf(line, " (%d) Abnormal termination (signal %d)", &logcode, &exitcode) == 2) { debug(D_BATCH, "job %" PRIbjid " completed abnormally with signal %d.", jobid, exitcode); info->exited_normally = 0; info->exit_signal = exitcode; } else { debug(D_BATCH, "job %" PRIbjid " completed with unknown status.", jobid); info->exited_normally = 0; info->exit_signal = 0; } memcpy(info_out, info, sizeof(*info)); free(info); return jobid; } } } if(itable_size(q->job_table) <= 0) return 0; if(stoptime != 0 && time(0) >= stoptime) return -1; if(process_pending()) return -1; sleep(1); } return -1; }
static zip_int64_t read_file(void *state, void *data, zip_uint64_t len, zip_source_cmd_t cmd) { struct read_file *ctx; char *buf; zip_uint64_t n; size_t i; ctx = (struct read_file *)state; buf = (char *)data; switch (cmd) { case ZIP_SOURCE_BEGIN_WRITE: if (ctx->fname == NULL) { zip_error_set(&ctx->error, ZIP_ER_OPNOTSUPP, 0); return -1; } return create_temp_output(ctx); case ZIP_SOURCE_COMMIT_WRITE: { mode_t mask; if (fclose(ctx->fout) < 0) { ctx->fout = NULL; zip_error_set(&ctx->error, ZIP_ER_WRITE, errno); } ctx->fout = NULL; if (rename(ctx->tmpname, ctx->fname) < 0) { zip_error_set(&ctx->error, ZIP_ER_RENAME, errno); return -1; } mask = umask(022); umask(mask); /* not much we can do if chmod fails except make the whole commit fail */ (void)chmod(ctx->fname, 0666&~mask); free(ctx->tmpname); ctx->tmpname = NULL; return 0; } case ZIP_SOURCE_CLOSE: if (ctx->fname) { fclose(ctx->f); ctx->f = NULL; } return 0; case ZIP_SOURCE_ERROR: return zip_error_to_data(&ctx->error, data, len); case ZIP_SOURCE_FREE: free(ctx->fname); free(ctx->tmpname); if (ctx->f) fclose(ctx->f); free(ctx); return 0; case ZIP_SOURCE_OPEN: if (ctx->fname) { if ((ctx->f=fopen(ctx->fname, "rb")) == NULL) { zip_error_set(&ctx->error, ZIP_ER_OPEN, errno); return -1; } } if (ctx->start > 0) { if (_zip_fseek_u(ctx->f, ctx->start, SEEK_SET, &ctx->error) < 0) { return -1; } } ctx->current = ctx->start; return 0; case ZIP_SOURCE_READ: if (ctx->end > 0) { n = ctx->end-ctx->current; if (n > len) { n = len; } } else { n = len; } if (n > SIZE_MAX) n = SIZE_MAX; if ((i=fread(buf, 1, (size_t)n, ctx->f)) == 0) { if (ferror(ctx->f)) { zip_error_set(&ctx->error, ZIP_ER_READ, errno); return -1; } } ctx->current += i; return (zip_int64_t)i; case ZIP_SOURCE_REMOVE: if (remove(ctx->fname) < 0) { zip_error_set(&ctx->error, ZIP_ER_REMOVE, errno); return -1; } return 0; case ZIP_SOURCE_ROLLBACK_WRITE: if (ctx->fout) { fclose(ctx->fout); ctx->fout = NULL; } (void)remove(ctx->tmpname); free(ctx->tmpname); ctx->tmpname = NULL; return 0; case ZIP_SOURCE_SEEK: { zip_int64_t new_current; int need_seek; zip_source_args_seek_t *args = ZIP_SOURCE_GET_ARGS(zip_source_args_seek_t, data, len, &ctx->error); if (args == NULL) return -1; need_seek = 1; switch (args->whence) { case SEEK_SET: new_current = args->offset; break; case SEEK_END: if (ctx->end == 0) { if (_zip_fseek(ctx->f, args->offset, SEEK_END, &ctx->error) < 0) { return -1; } if ((new_current = ftello(ctx->f)) < 0) { zip_error_set(&ctx->error, ZIP_ER_SEEK, errno); return -1; } need_seek = 0; } else { new_current = (zip_int64_t)ctx->end + args->offset; } break; case SEEK_CUR: new_current = (zip_int64_t)ctx->current + args->offset; break; default: zip_error_set(&ctx->error, ZIP_ER_INVAL, 0); return -1; } if (new_current < 0 || (zip_uint64_t)new_current < ctx->start || (ctx->end != 0 && (zip_uint64_t)new_current > ctx->end)) { zip_error_set(&ctx->error, ZIP_ER_INVAL, 0); return -1; } ctx->current = (zip_uint64_t)new_current; if (need_seek) { if (_zip_fseek_u(ctx->f, ctx->current, SEEK_SET, &ctx->error) < 0) { return -1; } } return 0; } case ZIP_SOURCE_SEEK_WRITE: { zip_source_args_seek_t *args; args = ZIP_SOURCE_GET_ARGS(zip_source_args_seek_t, data, len, &ctx->error); if (args == NULL) { return -1; } if (_zip_fseek(ctx->fout, args->offset, args->whence, &ctx->error) < 0) { return -1; } return 0; } case ZIP_SOURCE_STAT: { if (len < sizeof(ctx->st)) return -1; if (ctx->st.valid != 0) memcpy(data, &ctx->st, sizeof(ctx->st)); else { zip_stat_t *st; struct stat fst; int err; if (ctx->f) err = fstat(fileno(ctx->f), &fst); else err = stat(ctx->fname, &fst); if (err != 0) { zip_error_set(&ctx->error, ZIP_ER_READ, errno); return -1; } st = (zip_stat_t *)data; zip_stat_init(st); st->mtime = fst.st_mtime; st->valid |= ZIP_STAT_MTIME; if (ctx->end != 0) { st->size = ctx->end - ctx->start; st->valid |= ZIP_STAT_SIZE; } else if ((fst.st_mode&S_IFMT) == S_IFREG) { st->size = (zip_uint64_t)fst.st_size; st->valid |= ZIP_STAT_SIZE; } } return sizeof(ctx->st); } case ZIP_SOURCE_SUPPORTS: return ctx->supports; case ZIP_SOURCE_TELL: return (zip_int64_t)ctx->current; case ZIP_SOURCE_TELL_WRITE: { off_t ret = ftello(ctx->fout); if (ret < 0) { zip_error_set(&ctx->error, ZIP_ER_TELL, errno); return -1; } return ret; } case ZIP_SOURCE_WRITE: { size_t ret; clearerr(ctx->fout); ret = fwrite(data, 1, len, ctx->fout); if (ret != len || ferror(ctx->fout)) { zip_error_set(&ctx->error, ZIP_ER_WRITE, errno); return -1; } return (zip_int64_t)ret; } default: zip_error_set(&ctx->error, ZIP_ER_OPNOTSUPP, 0); return -1; } }
/* * Fetch a file */ static int fetch(char *URL, const char *path) { struct url *url; struct url_stat us; struct stat sb, nsb; struct xferstat xs; FILE *f, *of; size_t size, readcnt, wr; off_t count; char flags[8]; const char *slash; char *tmppath; int r; unsigned timeout; char *ptr; f = of = NULL; tmppath = NULL; timeout = 0; *flags = 0; count = 0; /* set verbosity level */ if (v_level > 1) strcat(flags, "v"); if (v_level > 2) fetchDebug = 1; /* parse URL */ url = NULL; if (*URL == '\0') { warnx("empty URL"); goto failure; } if ((url = fetchParseURL(URL)) == NULL) { warnx("%s: parse error", URL); goto failure; } /* if no scheme was specified, take a guess */ if (!*url->scheme) { if (!*url->host) strcpy(url->scheme, SCHEME_FILE); else if (strncasecmp(url->host, "ftp.", 4) == 0) strcpy(url->scheme, SCHEME_FTP); else if (strncasecmp(url->host, "www.", 4) == 0) strcpy(url->scheme, SCHEME_HTTP); } /* common flags */ switch (family) { case PF_INET: strcat(flags, "4"); break; case PF_INET6: strcat(flags, "6"); break; } /* FTP specific flags */ if (strcmp(url->scheme, SCHEME_FTP) == 0) { if (p_flag) strcat(flags, "p"); if (d_flag) strcat(flags, "d"); if (U_flag) strcat(flags, "l"); timeout = T_secs ? T_secs : ftp_timeout; } /* HTTP specific flags */ if (strcmp(url->scheme, SCHEME_HTTP) == 0 || strcmp(url->scheme, SCHEME_HTTPS) == 0) { if (d_flag) strcat(flags, "d"); if (A_flag) strcat(flags, "A"); timeout = T_secs ? T_secs : http_timeout; if (i_flag) { if (stat(i_filename, &sb)) { warn("%s: stat()", i_filename); goto failure; } url->ims_time = sb.st_mtime; strcat(flags, "i"); } } /* set the protocol timeout. */ fetchTimeout = timeout; /* just print size */ if (s_flag) { if (timeout) alarm(timeout); r = fetchStat(url, &us, flags); if (timeout) alarm(0); if (sigalrm || sigint) goto signal; if (r == -1) { warnx("%s", fetchLastErrString); goto failure; } if (us.size == -1) printf("Unknown\n"); else printf("%jd\n", (intmax_t)us.size); goto success; } /* * If the -r flag was specified, we have to compare the local * and remote files, so we should really do a fetchStat() * first, but I know of at least one HTTP server that only * sends the content size in response to GET requests, and * leaves it out of replies to HEAD requests. Also, in the * (frequent) case that the local and remote files match but * the local file is truncated, we have sufficient information * before the compare to issue a correct request. Therefore, * we always issue a GET request as if we were sure the local * file was a truncated copy of the remote file; we can drop * the connection later if we change our minds. */ sb.st_size = -1; if (!o_stdout) { r = stat(path, &sb); if (r == 0 && r_flag && S_ISREG(sb.st_mode)) { url->offset = sb.st_size; } else if (r == -1 || !S_ISREG(sb.st_mode)) { /* * Whatever value sb.st_size has now is either * wrong (if stat(2) failed) or irrelevant (if the * path does not refer to a regular file) */ sb.st_size = -1; } if (r == -1 && errno != ENOENT) { warnx("%s: stat()", path); goto failure; } } /* start the transfer */ if (timeout) alarm(timeout); f = fetchXGet(url, &us, flags); if (timeout) alarm(0); if (sigalrm || sigint) goto signal; if (f == NULL) { warnx("%s: %s", URL, fetchLastErrString); if (i_flag && (strcmp(url->scheme, SCHEME_HTTP) == 0 || strcmp(url->scheme, SCHEME_HTTPS) == 0) && fetchLastErrCode == FETCH_OK && strcmp(fetchLastErrString, "Not Modified") == 0) { /* HTTP Not Modified Response, return OK. */ r = 0; goto done; } else goto failure; } if (sigint) goto signal; /* check that size is as expected */ if (S_size) { if (us.size == -1) { warnx("%s: size unknown", URL); } else if (us.size != S_size) { warnx("%s: size mismatch: expected %jd, actual %jd", URL, (intmax_t)S_size, (intmax_t)us.size); goto failure; } } /* symlink instead of copy */ if (l_flag && strcmp(url->scheme, "file") == 0 && !o_stdout) { if (symlink(url->doc, path) == -1) { warn("%s: symlink()", path); goto failure; } goto success; } if (us.size == -1 && !o_stdout && v_level > 0) warnx("%s: size of remote file is not known", URL); if (v_level > 1) { if (sb.st_size != -1) fprintf(stderr, "local size / mtime: %jd / %ld\n", (intmax_t)sb.st_size, (long)sb.st_mtime); if (us.size != -1) fprintf(stderr, "remote size / mtime: %jd / %ld\n", (intmax_t)us.size, (long)us.mtime); } /* open output file */ if (o_stdout) { /* output to stdout */ of = stdout; } else if (r_flag && sb.st_size != -1) { /* resume mode, local file exists */ if (!F_flag && us.mtime && sb.st_mtime != us.mtime) { /* no match! have to refetch */ fclose(f); /* if precious, warn the user and give up */ if (R_flag) { warnx("%s: local modification time " "does not match remote", path); goto failure_keep; } } else if (url->offset > sb.st_size) { /* gap between what we asked for and what we got */ warnx("%s: gap in resume mode", URL); fclose(of); of = NULL; /* picked up again later */ } else if (us.size != -1) { if (us.size == sb.st_size) /* nothing to do */ goto success; if (sb.st_size > us.size) { /* local file too long! */ warnx("%s: local file (%jd bytes) is longer " "than remote file (%jd bytes)", path, (intmax_t)sb.st_size, (intmax_t)us.size); goto failure; } /* we got it, open local file */ if ((of = fopen(path, "r+")) == NULL) { warn("%s: fopen()", path); goto failure; } /* check that it didn't move under our feet */ if (fstat(fileno(of), &nsb) == -1) { /* can't happen! */ warn("%s: fstat()", path); goto failure; } if (nsb.st_dev != sb.st_dev || nsb.st_ino != sb.st_ino || nsb.st_size != sb.st_size) { warnx("%s: file has changed", URL); fclose(of); of = NULL; sb = nsb; /* picked up again later */ } } /* seek to where we left off */ if (of != NULL && fseeko(of, url->offset, SEEK_SET) != 0) { warn("%s: fseeko()", path); fclose(of); of = NULL; /* picked up again later */ } } else if (m_flag && sb.st_size != -1) { /* mirror mode, local file exists */ if (sb.st_size == us.size && sb.st_mtime == us.mtime) goto success; } if (of == NULL) { /* * We don't yet have an output file; either this is a * vanilla run with no special flags, or the local and * remote files didn't match. */ if (url->offset > 0) { /* * We tried to restart a transfer, but for * some reason gave up - so we have to restart * from scratch if we want the whole file */ url->offset = 0; if ((f = fetchXGet(url, &us, flags)) == NULL) { warnx("%s: %s", URL, fetchLastErrString); goto failure; } if (sigint) goto signal; } /* construct a temp file name */ if (sb.st_size != -1 && S_ISREG(sb.st_mode)) { if ((slash = strrchr(path, '/')) == NULL) slash = path; else ++slash; asprintf(&tmppath, "%.*s.fetch.XXXXXX.%s", (int)(slash - path), path, slash); if (tmppath != NULL) { if (mkstemps(tmppath, strlen(slash) + 1) == -1) { warn("%s: mkstemps()", path); goto failure; } of = fopen(tmppath, "w"); chown(tmppath, sb.st_uid, sb.st_gid); chmod(tmppath, sb.st_mode & ALLPERMS); } } if (of == NULL) of = fopen(path, "w"); if (of == NULL) { warn("%s: open()", path); goto failure; } } count = url->offset; /* start the counter */ stat_start(&xs, path, us.size, count); sigalrm = siginfo = sigint = 0; /* suck in the data */ setvbuf(f, NULL, _IOFBF, B_size); signal(SIGINFO, sig_handler); while (!sigint) { if (us.size != -1 && us.size - count < B_size && us.size - count >= 0) size = us.size - count; else size = B_size; if (siginfo) { stat_end(&xs); siginfo = 0; } if (size == 0) break; if ((readcnt = fread(buf, 1, size, f)) < size) { if (ferror(f) && errno == EINTR && !sigint) clearerr(f); else if (readcnt == 0) break; } stat_update(&xs, count += readcnt); for (ptr = buf; readcnt > 0; ptr += wr, readcnt -= wr) if ((wr = fwrite(ptr, 1, readcnt, of)) < readcnt) { if (ferror(of) && errno == EINTR && !sigint) clearerr(of); else break; } if (readcnt != 0) break; } if (!sigalrm) sigalrm = ferror(f) && errno == ETIMEDOUT; signal(SIGINFO, SIG_DFL); stat_end(&xs); /* * If the transfer timed out or was interrupted, we still want to * set the mtime in case the file is not removed (-r or -R) and * the user later restarts the transfer. */ signal: /* set mtime of local file */ if (!n_flag && us.mtime && !o_stdout && of != NULL && (stat(path, &sb) != -1) && sb.st_mode & S_IFREG) { struct timeval tv[2]; fflush(of); tv[0].tv_sec = (long)(us.atime ? us.atime : us.mtime); tv[1].tv_sec = (long)us.mtime; tv[0].tv_usec = tv[1].tv_usec = 0; if (utimes(tmppath ? tmppath : path, tv)) warn("%s: utimes()", tmppath ? tmppath : path); } /* timed out or interrupted? */ if (sigalrm) warnx("transfer timed out"); if (sigint) { warnx("transfer interrupted"); goto failure; } /* timeout / interrupt before connection completley established? */ if (f == NULL) goto failure; if (!sigalrm) { /* check the status of our files */ if (ferror(f)) warn("%s", URL); if (ferror(of)) warn("%s", path); if (ferror(f) || ferror(of)) goto failure; } /* did the transfer complete normally? */ if (us.size != -1 && count < us.size) { warnx("%s appears to be truncated: %jd/%jd bytes", path, (intmax_t)count, (intmax_t)us.size); goto failure_keep; } /* * If the transfer timed out and we didn't know how much to * expect, assume the worst (i.e. we didn't get all of it) */ if (sigalrm && us.size == -1) { warnx("%s may be truncated", path); goto failure_keep; } success: r = 0; if (tmppath != NULL && rename(tmppath, path) == -1) { warn("%s: rename()", path); goto failure_keep; } goto done; failure: if (of && of != stdout && !R_flag && !r_flag) if (stat(path, &sb) != -1 && (sb.st_mode & S_IFREG)) unlink(tmppath ? tmppath : path); if (R_flag && tmppath != NULL && sb.st_size == -1) rename(tmppath, path); /* ignore errors here */ failure_keep: r = -1; goto done; done: if (f) fclose(f); if (of && of != stdout) fclose(of); if (url) fetchFreeURL(url); if (tmppath != NULL) free(tmppath); return (r); }
/* Writes a buffer to the file stream * This function uses the POSIX fwrite function or equivalent * Returns the number of bytes written if successful, or -1 on error */ ssize_t libcfile_stream_write_buffer( libcfile_stream_t *stream, const uint8_t *buffer, size_t size, libcerror_error_t **error ) { libcfile_internal_stream_t *internal_stream = NULL; static char *function = "libcfile_stream_write_buffer"; ssize_t write_count = 0; if( stream == NULL ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid stream.", function ); return( -1 ); } internal_stream = (libcfile_internal_stream_t *) stream; if( internal_stream->stream == NULL ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_VALUE_MISSING, "%s: invalid stream - missing stream.", function ); return( -1 ); } if( buffer == NULL ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid buffer.", function ); return( -1 ); } if( size > (size_t) SSIZE_MAX ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_VALUE_EXCEEDS_MAXIMUM, "%s: invalid size value exceeds maximum.", function ); return( -1 ); } write_count = fwrite( (void *) buffer, 1, size, internal_stream->stream ); if( write_count == 0 ) { if( feof( internal_stream->stream ) == 0 ) { libcerror_system_set_error( error, LIBCERROR_ERROR_DOMAIN_IO, LIBCERROR_IO_ERROR_WRITE_FAILED, errno, "%s: unable to write to stream.", function ); clearerr( internal_stream->stream ); return( -1 ); } clearerr( internal_stream->stream ); } return( write_count ); }
static int globus_l_job_manager_parse_events( globus_l_job_manager_logfile_state_t * state) { int rc; int protocol_msg_type; time_t stamp; char jobid[129]; char nl[2]; int job_state; int exit_code; struct tm gmstamp, *gmstampp; fpos_t pos; SEG_JOB_MANAGER_DEBUG(SEG_JOB_MANAGER_DEBUG_INFO, ("globus_l_job_manager_parse_events() called\n")); fgetpos(state->fp, &pos); while ((rc = fscanf(state->fp, "%d;%ld;%128[^;];%d;%d%1[\n]", &protocol_msg_type, &stamp, jobid, &job_state, &exit_code, nl)) > 4) { if (rc == 4 && fscanf(state->fp, "%1[\n]", nl) != 1) { goto bad_line; } if (protocol_msg_type != 1) { goto bad_line; } gmstampp = globus_libc_gmtime_r(&stamp, &gmstamp); if (globus_l_time_is_newer(&state->start_timestamp, &gmstamp)) { /* Ignore events that occur before our start timestamp */ goto bad_line; } switch(job_state) { case GLOBUS_GRAM_PROTOCOL_JOB_STATE_PENDING: globus_scheduler_event_pending(stamp, jobid); break; case GLOBUS_GRAM_PROTOCOL_JOB_STATE_ACTIVE: globus_scheduler_event_active(stamp, jobid); break; case GLOBUS_GRAM_PROTOCOL_JOB_STATE_DONE: globus_scheduler_event_done(stamp, jobid, exit_code); break; case GLOBUS_GRAM_PROTOCOL_JOB_STATE_FAILED: globus_scheduler_event_failed(stamp, jobid, exit_code); break; default: goto bad_line; } bad_line: fgetpos(state->fp, &pos); } if (feof(state->fp)) { clearerr(state->fp); rc = SEG_JOB_MANAGER_ERROR_LOG_EOF; } else { rc = 0; } fsetpos(state->fp, &pos); SEG_JOB_MANAGER_DEBUG(SEG_JOB_MANAGER_DEBUG_INFO, ("globus_l_job_manager_parse_events() exits\n")); return rc; }
/* * ExecQueryUsingCursor: run a SELECT-like query using a cursor * * This feature allows result sets larger than RAM to be dealt with. * * Returns true if the query executed successfully, false otherwise. * * If pset.timing is on, total query time (exclusive of result-printing) is * stored into *elapsed_msec. */ static bool ExecQueryUsingCursor(const char *query, double *elapsed_msec) { bool OK = true; PGresult *results; PQExpBufferData buf; printQueryOpt my_popt = pset.popt; FILE *fout; bool is_pipe; bool is_pager = false; bool started_txn = false; int ntuples; int fetch_count; char fetch_cmd[64]; instr_time before, after; int flush_error; *elapsed_msec = 0; /* initialize print options for partial table output */ my_popt.topt.start_table = true; my_popt.topt.stop_table = false; my_popt.topt.prior_records = 0; if (pset.timing) INSTR_TIME_SET_CURRENT(before); /* if we're not in a transaction, start one */ if (PQtransactionStatus(pset.db) == PQTRANS_IDLE) { results = PQexec(pset.db, "BEGIN"); OK = AcceptResult(results) && (PQresultStatus(results) == PGRES_COMMAND_OK); PQclear(results); if (!OK) return false; started_txn = true; } /* Send DECLARE CURSOR */ initPQExpBuffer(&buf); appendPQExpBuffer(&buf, "DECLARE _psql_cursor NO SCROLL CURSOR FOR\n%s", query); results = PQexec(pset.db, buf.data); OK = AcceptResult(results) && (PQresultStatus(results) == PGRES_COMMAND_OK); PQclear(results); termPQExpBuffer(&buf); if (!OK) goto cleanup; if (pset.timing) { INSTR_TIME_SET_CURRENT(after); INSTR_TIME_SUBTRACT(after, before); *elapsed_msec += INSTR_TIME_GET_MILLISEC(after); } /* * In \gset mode, we force the fetch count to be 2, so that we will throw * the appropriate error if the query returns more than one row. */ if (pset.gset_prefix) fetch_count = 2; else fetch_count = pset.fetch_count; snprintf(fetch_cmd, sizeof(fetch_cmd), "FETCH FORWARD %d FROM _psql_cursor", fetch_count); /* prepare to write output to \g argument, if any */ if (pset.gfname) { if (!openQueryOutputFile(pset.gfname, &fout, &is_pipe)) { OK = false; goto cleanup; } if (is_pipe) disable_sigpipe_trap(); } else { fout = pset.queryFout; is_pipe = false; /* doesn't matter */ } /* clear any pre-existing error indication on the output stream */ clearerr(fout); for (;;) { if (pset.timing) INSTR_TIME_SET_CURRENT(before); /* get fetch_count tuples at a time */ results = PQexec(pset.db, fetch_cmd); if (pset.timing) { INSTR_TIME_SET_CURRENT(after); INSTR_TIME_SUBTRACT(after, before); *elapsed_msec += INSTR_TIME_GET_MILLISEC(after); } if (PQresultStatus(results) != PGRES_TUPLES_OK) { /* shut down pager before printing error message */ if (is_pager) { ClosePager(fout); is_pager = false; } OK = AcceptResult(results); Assert(!OK); PQclear(results); break; } if (pset.gset_prefix) { /* StoreQueryTuple will complain if not exactly one row */ OK = StoreQueryTuple(results); PQclear(results); break; } ntuples = PQntuples(results); if (ntuples < fetch_count) { /* this is the last result set, so allow footer decoration */ my_popt.topt.stop_table = true; } else if (fout == stdout && !is_pager) { /* * If query requires multiple result sets, hack to ensure that * only one pager instance is used for the whole mess */ fout = PageOutput(INT_MAX, &(my_popt.topt)); is_pager = true; } printQuery(results, &my_popt, fout, is_pager, pset.logfile); PQclear(results); /* after the first result set, disallow header decoration */ my_popt.topt.start_table = false; my_popt.topt.prior_records += ntuples; /* * Make sure to flush the output stream, so intermediate results are * visible to the client immediately. We check the results because if * the pager dies/exits/etc, there's no sense throwing more data at * it. */ flush_error = fflush(fout); /* * Check if we are at the end, if a cancel was pressed, or if there * were any errors either trying to flush out the results, or more * generally on the output stream at all. If we hit any errors * writing things to the stream, we presume $PAGER has disappeared and * stop bothering to pull down more data. */ if (ntuples < fetch_count || cancel_pressed || flush_error || ferror(fout)) break; } if (pset.gfname) { /* close \g argument file/pipe */ if (is_pipe) { pclose(fout); restore_sigpipe_trap(); } else fclose(fout); } else if (is_pager) { /* close transient pager */ ClosePager(fout); } cleanup: if (pset.timing) INSTR_TIME_SET_CURRENT(before); /* * We try to close the cursor on either success or failure, but on failure * ignore the result (it's probably just a bleat about being in an aborted * transaction) */ results = PQexec(pset.db, "CLOSE _psql_cursor"); if (OK) { OK = AcceptResult(results) && (PQresultStatus(results) == PGRES_COMMAND_OK); } PQclear(results); if (started_txn) { results = PQexec(pset.db, OK ? "COMMIT" : "ROLLBACK"); OK &= AcceptResult(results) && (PQresultStatus(results) == PGRES_COMMAND_OK); PQclear(results); } if (pset.timing) { INSTR_TIME_SET_CURRENT(after); INSTR_TIME_SUBTRACT(after, before); *elapsed_msec += INSTR_TIME_GET_MILLISEC(after); } return OK; }
int expand_main(int argc UNUSED_PARAM, char **argv) { /* Default 8 spaces for 1 tab */ const char *opt_t = "8"; FILE *file; unsigned tab_size; unsigned opt; int exit_status = EXIT_SUCCESS; #if ENABLE_FEATURE_EXPAND_LONG_OPTIONS static const char expand_longopts[] ALIGN1 = /* name, has_arg, val */ "initial\0" No_argument "i" "tabs\0" Required_argument "t" ; #endif #if ENABLE_FEATURE_UNEXPAND_LONG_OPTIONS static const char unexpand_longopts[] ALIGN1 = /* name, has_arg, val */ "first-only\0" No_argument "i" "tabs\0" Required_argument "t" "all\0" No_argument "a" ; #endif init_unicode(); if (ENABLE_EXPAND && (!ENABLE_UNEXPAND || applet_name[0] == 'e')) { IF_FEATURE_EXPAND_LONG_OPTIONS(applet_long_options = expand_longopts); opt = getopt32(argv, "it:", &opt_t); } else { IF_FEATURE_UNEXPAND_LONG_OPTIONS(applet_long_options = unexpand_longopts); /* -t NUM sets also -a */ opt_complementary = "ta"; opt = getopt32(argv, "ft:a", &opt_t); /* -f --first-only is the default */ if (!(opt & OPT_ALL)) opt |= OPT_INITIAL; } tab_size = xatou_range(opt_t, 1, UINT_MAX); argv += optind; if (!*argv) { *--argv = (char*)bb_msg_standard_input; } do { file = fopen_or_warn_stdin(*argv); if (!file) { exit_status = EXIT_FAILURE; continue; } if (ENABLE_EXPAND && (!ENABLE_UNEXPAND || applet_name[0] == 'e')) IF_EXPAND(expand(file, tab_size, opt)); else IF_UNEXPAND(unexpand(file, tab_size, opt)); /* Check and close the file */ if (fclose_if_not_stdin(file)) { bb_simple_perror_msg(*argv); exit_status = EXIT_FAILURE; } /* If stdin also clear EOF */ if (file == stdin) clearerr(file); } while (*++argv); /* Now close stdin also */ /* (if we didn't read from it, it's a no-op) */ if (fclose(stdin)) bb_perror_msg_and_die(bb_msg_standard_input); fflush_stdout_and_exit(exit_status); }
static char * readtty(const char *pr, char *src) { char canonb[LINESIZE]; char *cp, *cp2; int c; #ifdef TIOCSTI char ch; #endif (void)fputs(pr, stdout); (void)fflush(stdout); if (src != NULL && strlen(src) > sizeof(canonb) - 2) { (void)printf("too long to edit\n"); return src; } #ifndef TIOCSTI if (src != NULL) cp = copy(src, canonb); else cp = copy(__UNCONST(""), canonb); c = *cp; (void)fputs(canonb, stdout); (void)fflush(stdout); #else cp = src == NULL ? __UNCONST("") : src; while ((c = *cp++) != '\0') { if ((c_erase != _POSIX_VDISABLE && c == c_erase) || (c_kill != _POSIX_VDISABLE && c == c_kill)) { ch = '\\'; (void)ioctl(0, TIOCSTI, &ch); } ch = c; (void)ioctl(0, TIOCSTI, &ch); } cp = canonb; *cp = '\0'; #endif clearerr(stdin); cp2 = cp; while (cp2 < canonb + sizeof(canonb) - 1) { c = getc(stdin); sig_check(); if (c == EOF) { if (feof(stdin)) (void)putc('\n', stdout); break; } if (c == '\n') break; *cp2++ = c; } *cp2 = '\0'; if (c == EOF && ferror(stdin)) { cp = strlen(canonb) > 0 ? canonb : NULL; clearerr(stdin); return readtty(pr, cp); } #ifndef TIOCSTI if (cp == NULL || *cp == '\0') return src; if (ttyset == 0) return strlen(canonb) > 0 ? savestr(canonb) : NULL; /* * Do erase and kill. */ cp2 = cp; while (*cp != '\0') { c = *cp++; if (c_erase != _POSIX_VDISABLE && c == c_erase) { if (cp2 == canonb) continue; if (cp2[-1] == '\\') { cp2[-1] = c; continue; } cp2--; continue; } if (c_kill != _POSIX_VDISABLE && c == c_kill) { if (cp2 == canonb) continue; if (cp2[-1] == '\\') { cp2[-1] = c; continue; } cp2 = canonb; continue; } *cp2++ = c; } *cp2 = '\0'; #endif if (canonb[0] == '\0') return __UNCONST(""); return savestr(canonb); }
/** * Parse command-line arguments and update rdpSettings members accordingly. * @param settings pointer to rdpSettings struct to be updated. * @param argc number of arguments available. * @param argv string array of the arguments. * @param plugin_callback function to be called when a plugin needs to be loaded. * @param plugin_user_data pointer to be passed to the plugin_callback function. * @param ui_callback function to be called when a UI-specific argument is being processed. * @param ui_user_data pointer to be passed to the ui_callback function. * @return number of arguments that were parsed, or FREERDP_ARGS_PARSE_RESULT on failure or --version/--help */ int freerdp_parse_args(rdpSettings* settings, int argc, char** argv, ProcessPluginArgs plugin_callback, void* plugin_user_data, ProcessUIArgs ui_callback, void* ui_user_data) { int t; char* p; int i, j; int index = 1; int num_extensions = 0; RDP_PLUGIN_DATA* plugin_data; while (index < argc) { if ((strcmp("-h", argv[index]) == 0 ) || (strcmp("--help", argv[index]) == 0 )) { printf("\n" "FreeRDP - A Free Remote Desktop Protocol Client\n" "See http://www.freerdp.com for more information\n" "\n" "Usage: %s [options] server:port\n" " -0: connect to console session\n" " -a: set color depth in bits, default is 16\n" " -c: shell working directory\n" " -D: hide window decorations\n" " -T: window title\n" " -d: domain\n" " -f: fullscreen mode\n" " -g: set geometry, using format WxH or X%% or 'workarea', default is 1024x768\n" " -h: print this help\n" " -k: set keyboard layout ID\n" " -K: do not interfere with window manager bindings (don't grab keyboard)\n" " -n: hostname\n" " -o: console audio\n" " -p: password\n" " -s: set startup-shell\n" " -t: alternative port number, default is 3389\n" " -u: username\n" " -x: performance flags (m[odem], b[roadband] l[an], or a bit-mask)\n" " -X: embed into another window with a given XID.\n" " -z: enable compression\n" " --app: RemoteApp connection. This implies -g workarea\n" " --ext: load an extension\n" " --no-auth: disable authentication\n" " --authonly: authentication only, no UI\n" " --from-stdin: unspecified username, password, domain and hostname params are prompted\n" " --help: print this help\n" " --no-fastpath: disable fast-path\n" " --gdi: graphics rendering (hw, sw)\n" " --no-motion: don't send mouse motion events\n" " --no-osb: disable offscreen bitmaps\n" " --no-bmp-cache: disable bitmap cache\n" " --plugin: load a virtual channel plugin\n" " --rfx: enable RemoteFX\n" " --rfx-mode: RemoteFX operational flags (v[ideo], i[mage]), default is video\n" " --nsc: enable NSCodec (experimental)\n" " --disable-wallpaper: disables wallpaper\n" " --composition: enable desktop composition\n" " --disable-full-window-drag: disables full window drag\n" " --disable-menu-animations: disables menu animations\n" " --disable-theming: disables theming\n" " --kbd-list: list all keyboard layout ids used by -k\n" " --no-rdp: disable Standard RDP encryption\n" " --no-tls: disable TLS encryption\n" " --no-nla: disable network level authentication\n" " --ntlm: force NTLM authentication protocol version (1 or 2)\n" " --certificate-name: use the argument as the logon certificate, instead of the server name\n" " --ignore-certificate: ignore verification of logon certificate\n" " --sec: force protocol security (rdp, tls or nla)\n" " --secure-checksum: use salted checksums with Standard RDP encryption\n" " --version: print version information\n" "\n", argv[0]); return FREERDP_ARGS_PARSE_HELP; //TODO: What is the correct return } else if (strcmp("-a", argv[index]) == 0) { index++; if (index == argc) { printf("missing color depth\n"); return FREERDP_ARGS_PARSE_FAILURE; } settings->color_depth = atoi(argv[index]); } else if (strcmp("-u", argv[index]) == 0) { index++; if (index == argc) { printf("missing username\n"); return FREERDP_ARGS_PARSE_FAILURE; } settings->username = xstrdup(argv[index]); } else if (strcmp("-p", argv[index]) == 0) { index++; if (index == argc) { printf("missing password\n"); return FREERDP_ARGS_PARSE_FAILURE; } settings->password = xstrdup(argv[index]); settings->autologon = 1; /* * Overwrite original password which could be revealed by a simple "ps aux" command. * This approach won't hide the password length, but it is better than nothing. */ memset(argv[index], '*', strlen(argv[index])); } else if (strcmp("-d", argv[index]) == 0) { index++; if (index == argc) { printf("missing domain\n"); return FREERDP_ARGS_PARSE_FAILURE; } settings->domain = xstrdup(argv[index]); } else if (strcmp("-s", argv[index]) == 0) { index++; if (index == argc) { printf("missing shell\n"); return FREERDP_ARGS_PARSE_FAILURE; } settings->shell = xstrdup(argv[index]); } else if (strcmp("-c", argv[index]) == 0) { index++; if (index == argc) { printf("missing directory\n"); return FREERDP_ARGS_PARSE_FAILURE; } settings->directory = xstrdup(argv[index]); } else if (strcmp("-g", argv[index]) == 0) { index++; if (index == argc) { printf("missing dimensions\n"); return FREERDP_ARGS_PARSE_FAILURE; } if (strncmp("workarea", argv[index], 1) == 0) { settings->workarea = true; } else { settings->width = (uint16) strtol(argv[index], &p, 10); if (*p == 'x') { settings->height = (uint16) strtol(p + 1, &p, 10); } if (*p == '%') { settings->percent_screen = settings->width; if (settings->percent_screen <= 0 || settings->percent_screen > 100) { printf("invalid geometry percentage\n"); return FREERDP_ARGS_PARSE_FAILURE; } } else { if (ui_callback != NULL) ui_callback(settings, "-g", p, ui_user_data); } } } else if (strcmp("-f", argv[index]) == 0) { settings->fullscreen = true; } else if (strcmp("-D", argv[index]) == 0) { settings->decorations = false; } else if (strcmp("-T", argv[index]) == 0) { index++; if (index == argc) { printf("missing window title\n"); return FREERDP_ARGS_PARSE_FAILURE; } settings->window_title = xstrdup(argv[index]); } else if (strcmp("-t", argv[index]) == 0) { index++; if (index == argc) { printf("missing port number\n"); return FREERDP_ARGS_PARSE_FAILURE; } settings->port = atoi(argv[index]); } else if (strcmp("-k", argv[index]) == 0) { index++; if (index == argc) { printf("missing keyboard layout id\n"); return FREERDP_ARGS_PARSE_FAILURE; } sscanf(argv[index], "%X", &(settings->kbd_layout)); } else if (strcmp("-K", argv[index]) == 0) { settings->grab_keyboard = false; } else if (strcmp("-n", argv[index]) == 0) { index++; if (index == argc) { printf("missing client hostname\n"); return FREERDP_ARGS_PARSE_FAILURE; } strncpy(settings->client_hostname, argv[index], sizeof(settings->client_hostname) - 1); settings->client_hostname[sizeof(settings->client_hostname) - 1] = 0; } else if (strcmp("-o", argv[index]) == 0) { settings->console_audio = true; } else if (strcmp("-0", argv[index]) == 0) { settings->console_session = true; } else if (strcmp("-z", argv[index]) == 0) { settings->compression = true; } else if (strcmp("--ntlm", argv[index]) == 0) { index++; settings->ntlm_version = atoi(argv[index]); if (settings->ntlm_version != 2) settings->ntlm_version = 1; } else if (strcmp("--no-glyph-cache", argv[index]) == 0) { settings->glyph_cache = false; } else if (strcmp("--no-osb", argv[index]) == 0) { settings->offscreen_bitmap_cache = false; } else if (strcmp("--no-bmp-cache", argv[index]) == 0) { settings->bitmap_cache = false; } else if (strcmp("--no-auth", argv[index]) == 0) { settings->authentication = false; } else if (strcmp("--authonly", argv[index]) == 0) { settings->authentication_only = true; } else if (strcmp("--from-stdin", argv[index]) == 0) { settings->from_stdin = true; } else if (strcmp("--ignore-certificate", argv[index]) == 0) { settings->ignore_certificate = true; } else if (strcmp("--certificate-name", argv[index]) == 0) { index++; if (index == argc) { printf("missing certificate name\n"); return FREERDP_ARGS_PARSE_FAILURE; } settings->certificate_name = xstrdup(argv[index]); } else if (strcmp("--no-fastpath", argv[index]) == 0) { settings->fastpath_input = false; settings->fastpath_output = false; } else if (strcmp("--gdi", argv[index]) == 0) { index++; if (index == argc) { printf("missing GDI backend\n"); return FREERDP_ARGS_PARSE_FAILURE; } if (strncmp("sw", argv[index], 1) == 0) /* software */ { settings->sw_gdi = true; } else if (strncmp("hw", argv[index], 1) == 0) /* hardware */ { settings->sw_gdi = false; } else { printf("unknown GDI backend\n"); return FREERDP_ARGS_PARSE_FAILURE; } } else if (strcmp("--rfx", argv[index]) == 0) { settings->rfx_codec = true; settings->fastpath_output = true; settings->color_depth = 32; settings->frame_acknowledge = false; settings->performance_flags = PERF_FLAG_NONE; settings->large_pointer = true; } else if (strcmp("--rfx-mode", argv[index]) == 0) { index++; if (index == argc) { printf("missing RemoteFX mode flag\n"); return FREERDP_ARGS_PARSE_FAILURE; } if (argv[index][0] == 'v') /* video */ { settings->rfx_codec_mode = 0x00; } else if (argv[index][0] == 'i') /* image */ { settings->rfx_codec_mode = 0x02; } else { printf("unknown RemoteFX mode flag\n"); return FREERDP_ARGS_PARSE_FAILURE; } } else if (strcmp("--nsc", argv[index]) == 0) { settings->ns_codec = true; } else if (strcmp("--dump-rfx", argv[index]) == 0) { index++; if (index == argc) { printf("missing file name\n"); return FREERDP_ARGS_PARSE_FAILURE; } settings->dump_rfx_file = xstrdup(argv[index]); settings->dump_rfx = true; } else if (strcmp("--play-rfx", argv[index]) == 0) { index++; if (index == argc) { printf("missing file name\n"); return FREERDP_ARGS_PARSE_FAILURE; } settings->play_rfx_file = xstrdup(argv[index]); settings->play_rfx = true; } else if (strcmp("--fonts", argv[index]) == 0) { settings->smooth_fonts = true; } else if (strcmp("--disable-wallpaper", argv[index]) == 0) { settings->disable_wallpaper = true; } else if (strcmp("--disable-full-window-drag", argv[index]) == 0) { settings->disable_full_window_drag = true; } else if (strcmp("--disable-menu-animations", argv[index]) == 0) { settings->disable_menu_animations = true; } else if (strcmp("--disable-theming", argv[index]) == 0) { settings->disable_theming = true; } else if (strcmp("--composition", argv[index]) == 0) { settings->desktop_composition = true; } else if (strcmp("--no-motion", argv[index]) == 0) { settings->mouse_motion = false; } else if (strcmp("--app", argv[index]) == 0) { settings->remote_app = true; settings->rail_langbar_supported = true; settings->workarea = true; settings->performance_flags = PERF_DISABLE_WALLPAPER | PERF_DISABLE_FULLWINDOWDRAG; } else if (strcmp("-x", argv[index]) == 0) { index++; if (index == argc) { printf("missing performance flag\n"); return FREERDP_ARGS_PARSE_FAILURE; } if (argv[index][0] == 'm') /* modem */ { settings->performance_flags = PERF_DISABLE_WALLPAPER | PERF_DISABLE_FULLWINDOWDRAG | PERF_DISABLE_MENUANIMATIONS | PERF_DISABLE_THEMING; settings->connection_type = CONNECTION_TYPE_MODEM; } else if (argv[index][0] == 'b') /* broadband */ { settings->performance_flags = PERF_DISABLE_WALLPAPER; settings->connection_type = CONNECTION_TYPE_BROADBAND_HIGH; } else if (argv[index][0] == 'l') /* lan */ { settings->performance_flags = PERF_FLAG_NONE; settings->connection_type = CONNECTION_TYPE_LAN; } else { settings->performance_flags = strtol(argv[index], 0, 16); } } else if (strcmp("-X", argv[index]) == 0) { index++; if (index == argc) { printf("missing parent window XID\n"); return FREERDP_ARGS_PARSE_FAILURE; } settings->parent_window_xid = strtol(argv[index], NULL, 0); if (settings->parent_window_xid == 0) { printf("invalid parent window XID\n"); return FREERDP_ARGS_PARSE_FAILURE; } } else if (strcmp("--no-rdp", argv[index]) == 0) { settings->rdp_security = false; } else if (strcmp("--no-tls", argv[index]) == 0) { settings->tls_security = false; } else if (strcmp("--no-nla", argv[index]) == 0) { settings->nla_security = false; } else if (strcmp("--sec", argv[index]) == 0) { index++; if (index == argc) { printf("missing protocol security\n"); return FREERDP_ARGS_PARSE_FAILURE; } if (strncmp("rdp", argv[index], 1) == 0) /* Standard RDP */ { settings->rdp_security = true; settings->tls_security = false; settings->nla_security = false; settings->encryption = true; settings->encryption_method = ENCRYPTION_METHOD_40BIT | ENCRYPTION_METHOD_128BIT | ENCRYPTION_METHOD_FIPS; settings->encryption_level = ENCRYPTION_LEVEL_CLIENT_COMPATIBLE; } else if (strncmp("tls", argv[index], 1) == 0) /* TLS */ { settings->rdp_security = false; settings->tls_security = true; settings->nla_security = false; } else if (strncmp("nla", argv[index], 1) == 0) /* NLA */ { settings->rdp_security = false; settings->tls_security = false; settings->nla_security = true; } else { printf("unknown protocol security\n"); return FREERDP_ARGS_PARSE_FAILURE; } } else if (strcmp("--plugin", argv[index]) == 0) { index++; t = index; if (index == argc) { printf("missing plugin name\n"); return FREERDP_ARGS_PARSE_FAILURE; } plugin_data = NULL; if (strstr(argv[t], "rdpsnd")) settings->audio_playback = true; if (index < argc - 1 && strcmp("--data", argv[index + 1]) == 0) { index += 2; i = 0; while (index < argc && strcmp("--", argv[index]) != 0) { if (plugin_data == NULL) plugin_data = (RDP_PLUGIN_DATA*) xmalloc(sizeof(RDP_PLUGIN_DATA) * (i + 2)); else plugin_data = (RDP_PLUGIN_DATA*) xrealloc(plugin_data, sizeof(RDP_PLUGIN_DATA) * (i + 2)); if (strstr(argv[t], "drdynvc") && strstr(argv[index], "audin")) settings->audio_capture = true; plugin_data[i].size = sizeof(RDP_PLUGIN_DATA); plugin_data[i].data[0] = NULL; plugin_data[i].data[1] = NULL; plugin_data[i].data[2] = NULL; plugin_data[i].data[3] = NULL; plugin_data[i + 1].size = 0; for (j = 0, p = argv[index]; j < 4 && p != NULL; j++) { if (*p == '\'') { plugin_data[i].data[j] = p + 1; p = strchr(p + 1, '\''); if (p) *p++ = 0; } else plugin_data[i].data[j] = p; p = strchr(p, ':'); if (p != NULL) *p++ = 0; } index++; i++; } } if (plugin_callback != NULL) { if (!plugin_callback(settings, argv[t], plugin_data, plugin_user_data)) return FREERDP_ARGS_PARSE_FAILURE; } } else if (strcmp("--ext", argv[index]) == 0) { index++; if (index == argc) { printf("missing extension name\n"); return FREERDP_ARGS_PARSE_FAILURE; } if (num_extensions >= sizeof(settings->extensions) / sizeof(struct rdp_ext_set)) { printf("maximum extensions reached\n"); return FREERDP_ARGS_PARSE_FAILURE; } snprintf(settings->extensions[num_extensions].name, sizeof(settings->extensions[num_extensions].name), "%s", argv[index]); settings->extensions[num_extensions].data = NULL; if (index < argc - 1 && strcmp("--data", argv[index + 1]) == 0) { index += 2; settings->extensions[num_extensions].data = argv[index]; i = 0; while (index < argc && strcmp("--", argv[index]) != 0) { index++; i++; } } num_extensions++; } else if (strcmp("--secure-checksum", argv[index]) == 0) { settings->secure_checksum = true; } else if (strcmp("--version", argv[index]) == 0) { if (strlen(FREERDP_VERSION_SUFFIX)) printf("This is FreeRDP version %s-%s\n", FREERDP_VERSION_FULL, FREERDP_VERSION_SUFFIX); else printf("This is FreeRDP version %s\n", FREERDP_VERSION_FULL); return FREERDP_ARGS_PARSE_VERSION; } else if (argv[index][0] != '-') { freerdp_parse_hostname(settings, argv[index]); /* server is the last argument for the current session. arguments followed will be parsed for the next session. */ index++; if (settings->smooth_fonts) settings->performance_flags |= PERF_ENABLE_FONT_SMOOTHING; if (settings->desktop_composition) settings->performance_flags |= PERF_ENABLE_DESKTOP_COMPOSITION; if (settings->disable_wallpaper) settings->performance_flags |= PERF_DISABLE_WALLPAPER; if (settings->disable_full_window_drag) settings->performance_flags |= PERF_DISABLE_FULLWINDOWDRAG; if (settings->disable_menu_animations) settings->performance_flags |= PERF_DISABLE_MENUANIMATIONS; if (settings->disable_theming) settings->performance_flags |= PERF_DISABLE_THEMING; break; /* post process missing arguments */ } else { if (ui_callback != NULL) { t = ui_callback(settings, argv[index], (index + 1 < argc && argv[index + 1][0] != '-' ? argv[index + 1] : NULL), ui_user_data); if (t == 0) { printf("invalid option: %s\n", argv[index]); return FREERDP_ARGS_PARSE_FAILURE; } index += t - 1; } } index++; } /* --from-stdin will prompt for missing arguments only. You can prompt for username, password, domain and hostname to avoid disclosing these settings to ps. */ if (settings->from_stdin) { /* username */ if (NULL == settings->username) { char input[512]; input[0] = '\0'; printf("username: "******"%511s%*c", input) > 0) { settings->username = xstrdup(input); } } /* password */ if (NULL == settings->password) { settings->password = xmalloc(512 * sizeof(char)); if (isatty(STDIN_FILENO)) { freerdp_passphrase_read("password: "******"password: "******"%511s%*c", settings->password) <= 0) { free(settings->password); settings->password = NULL; } } } /* domain */ if (NULL == settings->domain) { char input[512]; input[0] = '\0'; printf("domain (control-D to skip): "); if (scanf("%511s%*c", input) > 0) { /* Try to catch the cases where the string is NULL-ish right at the get go */ if (input[0] != '\0' && !(input[0] == '.' && input[1] == '\0')) { settings->domain = xstrdup(input); } } if (feof(stdin)) { printf("\n"); clearerr(stdin); } } /* hostname */ if (NULL == settings->hostname) { char input[512]; input[0] = '\0'; printf("hostname: "); if (scanf("%511s%*c", input) > 0) { freerdp_parse_hostname(settings, input); } } } /* Must have a hostname. Do you? */ if (NULL == settings->hostname) { printf("missing server name\n"); return FREERDP_ARGS_PARSE_FAILURE; } else { return index; } }
static int read_file (const char *path) { FILE *fh; char key_buffer[4096]; char value_buffer[4096]; char *key_ptr; char *value_ptr; char *key_fields[256]; char *value_fields[256]; int key_fields_num; int value_fields_num; int status; int i; fh = fopen (path, "r"); if (fh == NULL) { ERROR ("protocols plugin: fopen (%s) failed: %s.", path, sstrerror (errno, key_buffer, sizeof (key_buffer))); return (-1); } status = -1; while (42) { clearerr (fh); key_ptr = fgets (key_buffer, sizeof (key_buffer), fh); if (key_ptr == NULL) { if (feof (fh) != 0) { status = 0; break; } else if (ferror (fh) != 0) { ERROR ("protocols plugin: Reading from %s failed.", path); break; } else { ERROR ("protocols plugin: fgets failed for an unknown reason."); break; } } /* if (key_ptr == NULL) */ value_ptr = fgets (value_buffer, sizeof (value_buffer), fh); if (value_ptr == NULL) { ERROR ("protocols plugin: read_file (%s): Could not read values line.", path); break; } key_ptr = strchr (key_buffer, ':'); if (key_ptr == NULL) { ERROR ("protocols plugin: Could not find protocol name in keys line."); break; } *key_ptr = 0; key_ptr++; value_ptr = strchr (value_buffer, ':'); if (value_ptr == NULL) { ERROR ("protocols plugin: Could not find protocol name " "in values line."); break; } *value_ptr = 0; value_ptr++; if (strcmp (key_buffer, value_buffer) != 0) { ERROR ("protocols plugin: Protocol names in keys and values lines " "don't match: `%s' vs. `%s'.", key_buffer, value_buffer); break; } key_fields_num = strsplit (key_ptr, key_fields, STATIC_ARRAY_SIZE (key_fields)); value_fields_num = strsplit (value_ptr, value_fields, STATIC_ARRAY_SIZE (value_fields)); if (key_fields_num != value_fields_num) { ERROR ("protocols plugin: Number of fields in keys and values lines " "don't match: %i vs %i.", key_fields_num, value_fields_num); break; } for (i = 0; i < key_fields_num; i++) { if (values_list != NULL) { char match_name[2 * DATA_MAX_NAME_LEN]; ssnprintf (match_name, sizeof (match_name), "%s:%s", key_buffer, key_fields[i]); if (ignorelist_match (values_list, match_name)) continue; } /* if (values_list != NULL) */ submit (key_buffer, key_fields[i], value_fields[i]); } /* for (i = 0; i < key_fields_num; i++) */ } /* while (42) */ fclose (fh); return (status); } /* int read_file */
int ps_decoder_test(cmd_ln_t *config, char const *sname, char const *expected) { ps_decoder_t *ps; mfcc_t **cepbuf; FILE *rawfh; int16 *buf; int16 const *bptr; size_t nread; size_t nsamps; int32 nfr, i, score, prob; char const *hyp; double n_speech, n_cpu, n_wall; ps_seg_t *seg; TEST_ASSERT(ps = ps_init(config)); /* Test it first with pocketsphinx_decode_raw() */ TEST_ASSERT(rawfh = fopen(DATADIR "/goforward.raw", "rb")); ps_decode_raw(ps, rawfh, -1); hyp = ps_get_hyp(ps, &score); prob = ps_get_prob(ps); printf("%s: %s (%d, %d)\n", sname, hyp, score, prob); TEST_EQUAL(0, strcmp(hyp, expected)); TEST_ASSERT(prob <= 0); ps_get_utt_time(ps, &n_speech, &n_cpu, &n_wall); printf("%.2f seconds speech, %.2f seconds CPU, %.2f seconds wall\n", n_speech, n_cpu, n_wall); printf("%.2f xRT (CPU), %.2f xRT (elapsed)\n", n_cpu / n_speech, n_wall / n_speech); /* Test it with ps_process_raw() */ clearerr(rawfh); fseek(rawfh, 0, SEEK_END); nsamps = ftell(rawfh) / sizeof(*buf); fseek(rawfh, 0, SEEK_SET); TEST_EQUAL(0, ps_start_utt(ps)); nsamps = 2048; buf = ckd_calloc(nsamps, sizeof(*buf)); while (!feof(rawfh)) { nread = fread(buf, sizeof(*buf), nsamps, rawfh); ps_process_raw(ps, buf, nread, FALSE, FALSE); } TEST_EQUAL(0, ps_end_utt(ps)); hyp = ps_get_hyp(ps, &score); prob = ps_get_prob(ps); printf("%s: %s (%d, %d)\n", sname, hyp, score, prob); TEST_EQUAL(0, strcmp(hyp, expected)); ps_get_utt_time(ps, &n_speech, &n_cpu, &n_wall); printf("%.2f seconds speech, %.2f seconds CPU, %.2f seconds wall\n", n_speech, n_cpu, n_wall); printf("%.2f xRT (CPU), %.2f xRT (elapsed)\n", n_cpu / n_speech, n_wall / n_speech); /* Now read the whole file and produce an MFCC buffer. */ clearerr(rawfh); fseek(rawfh, 0, SEEK_END); nsamps = ftell(rawfh) / sizeof(*buf); fseek(rawfh, 0, SEEK_SET); bptr = buf = ckd_realloc(buf, nsamps * sizeof(*buf)); TEST_EQUAL(nsamps, fread(buf, sizeof(*buf), nsamps, rawfh)); fe_process_frames(ps->acmod->fe, &bptr, &nsamps, NULL, &nfr, NULL); cepbuf = ckd_calloc_2d(nfr + 1, fe_get_output_size(ps->acmod->fe), sizeof(**cepbuf)); fe_start_utt(ps->acmod->fe); fe_process_frames(ps->acmod->fe, &bptr, &nsamps, cepbuf, &nfr, NULL); fe_end_utt(ps->acmod->fe, cepbuf[nfr], &i); /* Decode it with process_cep() */ TEST_EQUAL(0, ps_start_utt(ps)); for (i = 0; i < nfr; ++i) { ps_process_cep(ps, cepbuf + i, 1, FALSE, FALSE); } TEST_EQUAL(0, ps_end_utt(ps)); hyp = ps_get_hyp(ps, &score); prob = ps_get_prob(ps); printf("%s: %s (%d, %d)\n", sname, hyp, score, prob); TEST_EQUAL(0, strcmp(hyp, expected)); TEST_ASSERT(prob <= 0); for (seg = ps_seg_iter(ps); seg; seg = ps_seg_next(seg)) { char const *word; int sf, ef; int32 post, lscr, ascr, lback; word = ps_seg_word(seg); ps_seg_frames(seg, &sf, &ef); post = ps_seg_prob(seg, &ascr, &lscr, &lback); printf("%s (%d:%d) P(w|o) = %f ascr = %d lscr = %d lback = %d post=%d\n", word, sf, ef, logmath_exp(ps_get_logmath(ps), post), ascr, lscr, lback, post); } ps_get_utt_time(ps, &n_speech, &n_cpu, &n_wall); printf("%.2f seconds speech, %.2f seconds CPU, %.2f seconds wall\n", n_speech, n_cpu, n_wall); printf("%.2f xRT (CPU), %.2f xRT (elapsed)\n", n_cpu / n_speech, n_wall / n_speech); ps_get_all_time(ps, &n_speech, &n_cpu, &n_wall); printf("TOTAL: %.2f seconds speech, %.2f seconds CPU, %.2f seconds wall\n", n_speech, n_cpu, n_wall); printf("TOTAL: %.2f xRT (CPU), %.2f xRT (elapsed)\n", n_cpu / n_speech, n_wall / n_speech); fclose(rawfh); ps_free(ps); cmd_ln_free_r(config); ckd_free_2d(cepbuf); ckd_free(buf); return 0; }
void test_sio3(void) { FILE *f; static char buf[1024]; int i, j; if ((f = fopen(TMPFILE, "w+")) == NULL) { fail("fopen-5"); return; } pr("fwrite"); for (i=31; i<=527; i += 31) { memset(buf, i, i); if (fwrite(buf, 1, i, f) != i) fail("fwrite-1"); } rewind(f); pr("fread"); for (i=31; i<=527; i += 31) { memset(buf, i, i); if (fread(buf, 1, i, f) != i) fail("fread-1"); for (j=0; j<i; j++) { if ((buf[j] & 0xFF) != i % 256) break; } if (j < i) { fail("fread-2"); break; } } if (fclose(f)) fail("fclose-5"); if ((f = fopen(TMPFILE, "w+")) == NULL) { fail("fopen-5"); return; } for (i=0; i<1024; i++) buf[i] = '5'; for (i=0; i<16; i++) { if (fwrite(buf, 1, 1024, f) != 1024) { fail("fwrite-2"); break; } } rewind(f); for (i=0; i<16; i++) { if (fread(buf, 1, 1024, f) != 1024) { fail("fread-3"); break; } } if (fgetc(f) != EOF) fail("fread-4"); clearerr(f); rewind(f); pr("fseek/ftell"); if (fseek(f, 0, SEEK_END)) fail("fseek-1"); if (ftell(f) != 16384) fail("ftell-1"); if (fseek(f, 8100, SEEK_SET)) fail("fseek-2"); if (ftell(f) != 8100) fail("fseek-3"); if (fseek(f, 1900, SEEK_CUR)) fail("fseek-4"); if (ftell(f) != 10000) fail("fseek-5"); fclose(f); unlink(TMPFILE); }
/* * Read from serial, when we have a packet write it to tun. No output * buffering, input buffered by stdio. */ void serial_to_tun(FILE *inslip, int outfd) { static union { unsigned char inbuf[2000]; struct ip iphdr; } uip; static int inbufptr = 0; int ret; unsigned char c; #ifdef linux ret = fread(&c, 1, 1, inslip); if (ret == -1 || ret == 0) { err(1, "serial_to_tun: read"); } goto after_fread; #endif read_more: if (inbufptr >= sizeof(uip.inbuf)) { inbufptr = 0; } ret = fread(&c, 1, 1, inslip); #ifdef linux after_fread: #endif if (ret == -1) { err(1, "serial_to_tun: read"); } if (ret == 0) { clearerr(inslip); return; fprintf(stderr, "serial_to_tun: EOF\n"); exit(1); } /* fprintf(stderr, ".");*/ switch (c) { case SLIP_END: if (inbufptr > 0) { /* * Sanity checks. */ #define DEBUG_LINE_MARKER '\r' int ecode; ecode = check_ip(&uip.iphdr, inbufptr); if (ecode < 0 && inbufptr == 8 && strncmp(uip.inbuf, "=IPA", 4) == 0) { static struct in_addr ipa; inbufptr = 0; if (memcmp(&ipa, &uip.inbuf[4], sizeof(ipa)) == 0) { break; } /* New address. */ if (ipa.s_addr != 0) { #ifdef linux ssystem("route delete -net %s netmask %s dev %s", inet_ntoa(ipa), "255.255.255.255", tundev); #else ssystem("route delete -net %s -netmask %s -interface %s", inet_ntoa(ipa), "255.255.255.255", tundev); #endif } memcpy(&ipa, &uip.inbuf[4], sizeof(ipa)); if (ipa.s_addr != 0) { #ifdef linux ssystem("route add -net %s netmask %s dev %s", inet_ntoa(ipa), "255.255.255.255", tundev); #else ssystem("route add -net %s -netmask %s -interface %s", inet_ntoa(ipa), "255.255.255.255", tundev); #endif } break; } else if (ecode < 0) { /* * If sensible ASCII string, print it as debug info! */ if (uip.inbuf[0] == DEBUG_LINE_MARKER) { fwrite(uip.inbuf + 1, inbufptr - 1, 1, stderr); } else if (is_sensible_string(uip.inbuf, inbufptr)) { fwrite(uip.inbuf, inbufptr, 1, stderr); } else { fprintf(stderr, "serial_to_tun: drop packet len=%d ecode=%d\n", inbufptr, ecode); } inbufptr = 0; break; } PROGRESS("s"); if (dhsock != -1) { struct ip *ip = (void *)uip.inbuf; if (ip->ip_p == 17 && ip->ip_dst == 0xffffffff /* UDP and broadcast */ && ip->uh_sport == ntohs(BOOTPC) && ip->uh_dport == ntohs(BOOTPS)) { relay_dhcp_to_server(ip, inbufptr); inbufptr = 0; } } if (write(outfd, uip.inbuf, inbufptr) != inbufptr) { err(1, "serial_to_tun: write"); } inbufptr = 0; } break; case SLIP_ESC: if (fread(&c, 1, 1, inslip) != 1) { clearerr(inslip); /* Put ESC back and give up! */ ungetc(SLIP_ESC, inslip); return; } switch (c) { case SLIP_ESC_END: c = SLIP_END; break; case SLIP_ESC_ESC: c = SLIP_ESC; break; } /* FALLTHROUGH */ default: uip.inbuf[inbufptr++] = c; break; } goto read_more; }
/** alert_data *GetAlertData(FILE *fp) * Returns alert data for the file specified */ alert_data *GetAlertData(int flag, FILE *fp) { int _r = 0, issyscheck = 0; size_t log_size = 0; char *p; char *alertid = NULL; char *date = NULL; char *comment = NULL; char *location = NULL; char *srcip = NULL; char *dstip = NULL; char *user = NULL; char *group = NULL; char *filename = NULL; char *old_md5 = NULL; char *new_md5 = NULL; char *old_sha1 = NULL; char *new_sha1 = NULL; char **log = NULL; #ifdef LIBGEOIP_ENABLED char *geoipdatasrc = NULL; char *geoipdatadst = NULL; #endif int level = 0, rule = 0, srcport = 0, dstport = 0; char str[OS_BUFFER_SIZE+1]; str[OS_BUFFER_SIZE]='\0'; while(fgets(str, OS_BUFFER_SIZE, fp) != NULL) { /* Enf of alert */ if(strcmp(str, "\n") == 0 && log_size > 0) { /* Found in here */ if(_r == 2) { alert_data *al_data; os_calloc(1, sizeof(alert_data), al_data); al_data->alertid = alertid; al_data->level = level; al_data->rule = rule; al_data->location = location; al_data->comment = comment; al_data->group = group; al_data->log = log; al_data->srcip = srcip; al_data->srcport = srcport; al_data->dstip = dstip; al_data->dstport = dstport; al_data->user = user; al_data->date = date; al_data->filename = filename; #ifdef LIBGEOIP_ENABLED al_data->geoipdatasrc = geoipdatasrc; al_data->geoipdatadst = geoipdatadst; #endif al_data->old_md5 = old_md5; al_data->new_md5 = new_md5; al_data->old_sha1 = old_sha1; al_data->new_sha1 = new_sha1; return(al_data); } _r = 0; } /* Checking for the header */ if(strncmp(ALERT_BEGIN, str, ALERT_BEGIN_SZ) == 0) { char *m; size_t z = 0; p = str + ALERT_BEGIN_SZ + 1; m = strstr(p, ":"); if (!m) { continue; } z = strlen(p) - strlen(m); os_realloc(alertid, (z + 1)*sizeof(char), alertid); strncpy(alertid, p, z); alertid[z] = '\0'; /* Searching for email flag */ p = strchr(p, ' '); if(!p) { continue; } p++; /* Checking for the flags */ if((flag & CRALERT_MAIL_SET) && (strncmp(ALERT_MAIL, p, ALERT_MAIL_SZ) != 0)) { continue; } p = strchr(p, '-'); if(p) { p++; free(group); os_strdup(p, group); /* Cleaning new line from group */ os_clearnl(group, p); if(group != NULL && strstr(group, "syscheck") != NULL) { issyscheck = 1; } } /* Searching for active-response flag */ _r = 1; continue; } if(_r < 1) continue; /*** Extract information from the event ***/ /* r1 means: 2006 Apr 13 16:15:17 /var/log/auth.log */ if(_r == 1) { /* Clear new line */ os_clearnl(str, p); p = strchr(str, ':'); if(p) { p = strchr(p, ' '); if(p) { *p = '\0'; p++; } else { /* If p is null it is because strchr failed */ merror("ZZZ: 1() Merror date or location not NULL"); goto l_error; } } /* If not, str is date and p is the location */ if(date || location || !p) { merror("ZZZ Merror date or location not NULL or p is NULL"); goto l_error; } os_strdup(str, date); os_strdup(p, location); _r = 2; log_size = 0; continue; } else if(_r == 2) { /* Rule begin */ if(strncmp(RULE_BEGIN, str, RULE_BEGIN_SZ) == 0) { os_clearnl(str,p); p = str + RULE_BEGIN_SZ; rule = atoi(p); p = strchr(p, ' '); if(p) { p++; p = strchr(p, ' '); if(p) p++; } if(!p) goto l_error; level = atoi(p); /* Getting the comment */ p = strchr(p, '\''); if(!p) goto l_error; p++; os_strdup(p, comment); /* Must have the closing \' */ p = strrchr(comment, '\''); if(p) { *p = '\0'; } else { goto l_error; } } /* srcip */ else if(strncmp(SRCIP_BEGIN, str, SRCIP_BEGIN_SZ) == 0) { os_clearnl(str,p); p = str + SRCIP_BEGIN_SZ; os_strdup(p, srcip); } #ifdef LIBGEOIP_ENABLED /* GeoIP Source Location */ else if (strncmp(GEOIP_BEGIN_SRC, str, GEOIP_BEGIN_SRC_SZ) == 0) { os_clearnl(str,p); p = str + GEOIP_BEGIN_SRC_SZ; os_strdup(p, geoipdatasrc); } #endif /* srcport */ else if(strncmp(SRCPORT_BEGIN, str, SRCPORT_BEGIN_SZ) == 0) { os_clearnl(str,p); p = str + SRCPORT_BEGIN_SZ; srcport = atoi(p); } /* dstip */ else if(strncmp(DSTIP_BEGIN, str, DSTIP_BEGIN_SZ) == 0) { os_clearnl(str,p); p = str + DSTIP_BEGIN_SZ; os_strdup(p, dstip); } #ifdef LIBGEOIP_ENABLED /* GeoIP Destination Location */ else if (strncmp(GEOIP_BEGIN_DST, str, GEOIP_BEGIN_DST_SZ) == 0) { os_clearnl(str,p); p = str + GEOIP_BEGIN_DST_SZ; os_strdup(p, geoipdatadst); } #endif /* dstport */ else if(strncmp(DSTPORT_BEGIN, str, DSTPORT_BEGIN_SZ) == 0) { os_clearnl(str,p); p = str + DSTPORT_BEGIN_SZ; dstport = atoi(p); } /* username */ else if(strncmp(USER_BEGIN, str, USER_BEGIN_SZ) == 0) { os_clearnl(str,p); p = str + USER_BEGIN_SZ; os_strdup(p, user); } /* Old MD5 */ else if(strncmp(OLDMD5_BEGIN, str, OLDMD5_BEGIN_SZ) == 0) { os_clearnl(str,p); p = str + OLDMD5_BEGIN_SZ; os_strdup(p, old_md5); } /* New MD5 */ else if(strncmp(NEWMD5_BEGIN, str, NEWMD5_BEGIN_SZ) == 0) { os_clearnl(str,p); p = str + NEWMD5_BEGIN_SZ; os_strdup(p, new_md5); } /* Old SHA1 */ else if(strncmp(OLDSHA1_BEGIN, str, OLDSHA1_BEGIN_SZ) == 0) { os_clearnl(str,p); p = str + OLDSHA1_BEGIN_SZ; os_strdup(p, old_sha1); } /* New SHA1 */ else if(strncmp(NEWSHA1_BEGIN, str, NEWSHA1_BEGIN_SZ) == 0) { os_clearnl(str,p); p = str + NEWSHA1_BEGIN_SZ; os_strdup(p, new_sha1); } /* It is a log message */ else if(log_size < 20) { os_clearnl(str,p); if(issyscheck == 1) { if(strncmp(str, "Integrity checksum changed for: '",33) == 0) { filename = strdup(str+33); if(filename) { filename[strlen(filename) -1] = '\0'; } } issyscheck = 0; } os_realloc(log, (log_size +2)*sizeof(char *), log); os_strdup(str, log[log_size]); log_size++; log[log_size] = NULL; } } continue; l_error: /* Freeing the memory */ _r = 0; if(date) { free(date); date = NULL; } if(location) { free(location); location = NULL; } if(comment) { free(comment); comment = NULL; } if(srcip) { free(srcip); srcip = NULL; } #ifdef LIBGEOIP_ENABLED if(geoipdatasrc) { free(geoipdatasrc); geoipdatasrc = NULL; } if(geoipdatadst) { free(geoipdatadst); geoipdatadst = NULL; } #endif if(user) { free(user); user = NULL; } if(filename) { free(filename); filename = NULL; } if(group) { free(group); group = NULL; } if(old_md5) { free(old_md5); old_md5 = NULL; } if(new_md5) { free(new_md5); new_md5 = NULL; } if(old_sha1) { free(old_sha1); old_sha1 = NULL; } if(new_sha1) { free(new_sha1); new_sha1 = NULL; } while(log_size > 0) { log_size--; if(log[log_size]) { free(log[log_size]); log[log_size] = NULL; } } } if(alertid) { free(alertid); alertid = NULL; } if(group) { free(group); group = NULL; } if(location) { free(location); location = NULL; } if(date) { free(date); date = NULL; } while(log_size > 0) { log_size--; if(log[log_size]) { free(log[log_size]); log[log_size] = NULL; } } free(log); free(comment); free(srcip); free(dstip); free(user); free(old_md5); free(new_md5); free(old_sha1); free(new_sha1); free(filename); /* We need to clean end of file before returning */ clearerr(fp); return(NULL); }
/*--------------------------------------------------------------------*/ int main(int ac, char *av[]) { FILE *stream; char buf[10]; int nr, fd; int lc; /* * parse standard options */ tst_parse_opts(ac, av, NULL, NULL); tst_tmpdir(); local_flag = PASSED; for (lc = 0; TEST_LOOPING(lc); lc++) { local_flag = PASSED; sprintf(tempfile, "stream05.%d", getpid()); /*--------------------------------------------------------------------*/ //block0: if ((stream = fopen(tempfile, "a+")) == NULL) { tst_brkm(TFAIL, NULL, "fopen(%s) a+ failed: %s", tempfile, strerror(errno)); } fprintf(stream, "a"); fclose(stream); if ((stream = fopen(tempfile, "r+")) == NULL) { tst_brkm(TFAIL, NULL, "fopen(%s) r+ failed: %s", tempfile, strerror(errno)); } /* check that ferror returns zero */ if (ferror(stream) != 0) { tst_resm(TFAIL, "ferror did not return zero: %s", strerror(errno)); local_flag = FAILED; } if (local_flag == PASSED) { tst_resm(TPASS, "Test passed in block0."); } else { tst_resm(TFAIL, "Test failed in block0."); } local_flag = PASSED; /*--------------------------------------------------------------------*/ //block1: /* check that fileno returns valid file descriptor */ fd = fileno(stream); if ((nr = read(fd, buf, 1)) < 0) { tst_brkm(TFAIL, NULL, "read failed: %s", strerror(errno)); } if (nr != 1) { tst_resm(TFAIL, "read did not read right number"); local_flag = FAILED; } if (buf[0] != 'a') { tst_resm(TFAIL, "read returned bad values"); local_flag = FAILED; } if (local_flag == PASSED) { tst_resm(TPASS, "Test passed in block1."); } else { tst_resm(TFAIL, "Test failed in block1."); } local_flag = PASSED; /*--------------------------------------------------------------------*/ //block2: /* read to EOF and ensure feof returns non-zero */ fclose(stream); if ((stream = fopen(tempfile, "r+")) == NULL) { tst_brkm(TFAIL, NULL, "fopen(%s) r+ failed: %s", tempfile, strerror(errno)); } if (feof(stream) != 0) { tst_resm(TFAIL, "feof returned non-zero when it should not: %s", strerror(errno)); local_flag = FAILED; } fread(buf, 1, 2, stream); /* read to EOF */ if (feof(stream) == 0) { tst_resm(TFAIL, "feof returned zero when it should not: %s", strerror(errno)); local_flag = FAILED; } if (local_flag == PASSED) { tst_resm(TPASS, "Test passed in block2."); } else { tst_resm(TFAIL, "Test failed in block2."); } local_flag = PASSED; /*--------------------------------------------------------------------*/ //block3: /* ensure clearerr works */ clearerr(stream); if (feof(stream) != 0) { tst_resm(TFAIL, "clearerr failed: %s", strerror(errno)); local_flag = FAILED; } if (local_flag == PASSED) { tst_resm(TPASS, "Test passed in block3."); } else { tst_resm(TFAIL, "Test failed in block3."); } local_flag = PASSED; /*--------------------------------------------------------------------*/ //block4: /* test fopen "b" flags -- should be allowed but ignored */ (void)fclose(stream); if ((stream = fopen(tempfile, "rb")) == NULL) { tst_brkm(TFAIL, NULL, "fopen(%s) rb failed: %s", tempfile, strerror(errno)); } (void)fclose(stream); if ((stream = fopen(tempfile, "wb")) == NULL) { tst_brkm(TFAIL, NULL, "fopen(%s) wb failed: %s", tempfile, strerror(errno)); } (void)fclose(stream); if ((stream = fopen(tempfile, "ab")) == NULL) { tst_brkm(TFAIL, NULL, "fopen(%s) ab failed: %s", tempfile, strerror(errno)); } (void)fclose(stream); if ((stream = fopen(tempfile, "rb+")) == NULL) { tst_brkm(TFAIL, NULL, "fopen(%s) rb+ failed: %s", tempfile, strerror(errno)); } (void)fclose(stream); if ((stream = fopen(tempfile, "wb+")) == NULL) { tst_brkm(TFAIL, NULL, "fopen(%s) wb+ failed: %s", tempfile, strerror(errno)); } (void)fclose(stream); if ((stream = fopen(tempfile, "ab+")) == NULL) { tst_brkm(TFAIL, NULL, "fopen(%s) ab+ failed: %s", tempfile, strerror(errno)); } (void)fclose(stream); tst_resm(TPASS, "Test passed in block4."); /*--------------------------------------------------------------------*/ unlink(tempfile); } /* end for */ tst_rmdir(); tst_exit(); }
/***************************************************************************** * config_SaveConfigFile: Save a module's config options. ***************************************************************************** * It's no use to save the config options that kept their default values, so * we'll try to be a bit clever here. * * When we save we mustn't delete the config options of the modules that * haven't been loaded. So we cannot just create a new config file with the * config structures we've got in memory. * I don't really know how to deal with this nicely, so I will use a completly * dumb method ;-) * I will load the config file in memory, but skipping all the sections of the * modules we want to save. Then I will create a brand new file, dump the file * loaded in memory and then append the sections of the modules we want to * save. * Really stupid no ? *****************************************************************************/ static int SaveConfigFile (vlc_object_t *p_this) { module_t *p_parser; char *permanent = NULL, *temporary = NULL; if( config_PrepareDir( p_this ) ) { msg_Err( p_this, "no configuration directory" ); return -1; } /* List all available modules */ module_t **list = module_list_get (NULL); char *bigbuf = NULL; size_t bigsize = 0; FILE *file = config_OpenConfigFile (p_this); if (file != NULL) { struct stat st; /* Some users make vlcrc read-only to prevent changes. * The atomic replacement scheme breaks this "feature", * so we check for read-only by hand. */ if (fstat (fileno (file), &st) || !(st.st_mode & S_IWUSR)) { msg_Err (p_this, "configuration file is read-only"); goto error; } bigsize = (st.st_size < LONG_MAX) ? st.st_size : 0; bigbuf = malloc (bigsize + 1); if (bigbuf == NULL) goto error; /* backup file into memory, we only need to backup the sections we * won't save later on */ char *p_index = bigbuf; char *line = NULL; size_t bufsize; ssize_t linelen; bool backup = false; while ((linelen = getline (&line, &bufsize, file)) != -1) { char *p_index2; if ((line[0] == '[') && (p_index2 = strchr(line,']'))) { /* we found a new section, check if we need to do a backup */ backup = true; for (int i = 0; (p_parser = list[i]) != NULL; i++) { if (!strncmp (line + 1, p_parser->psz_object_name, strlen (p_parser->psz_object_name))) { backup = false; /* no, we will rewrite it! */ break; } } } /* save line if requested and line is valid (doesn't begin with a * space, tab, or eol) */ if (backup && !memchr ("\n\t ", line[0], 3)) { memcpy (p_index, line, linelen); p_index += linelen; } } fclose (file); file = NULL; free (line); *p_index = '\0'; bigsize = p_index - bigbuf; } /* * Save module config in file */ permanent = config_GetConfigFile (p_this); if (!permanent) { module_list_free (list); goto error; } if (asprintf (&temporary, "%s.%u", permanent, getpid ()) == -1) { temporary = NULL; module_list_free (list); goto error; } /* Configuration lock must be taken before vlcrc serializer below. */ vlc_rwlock_rdlock (&config_lock); /* The temporary configuration file is per-PID. Therefore SaveConfigFile() * should be serialized against itself within a given process. */ static vlc_mutex_t lock = VLC_STATIC_MUTEX; vlc_mutex_lock (&lock); int fd = vlc_open (temporary, O_CREAT|O_WRONLY|O_TRUNC, S_IRUSR|S_IWUSR); if (fd == -1) { vlc_rwlock_unlock (&config_lock); vlc_mutex_unlock (&lock); module_list_free (list); goto error; } file = fdopen (fd, "wt"); if (file == NULL) { msg_Err (p_this, "cannot create configuration file: %m"); vlc_rwlock_unlock (&config_lock); close (fd); vlc_mutex_unlock (&lock); module_list_free (list); goto error; } fprintf( file, "\xEF\xBB\xBF###\n" "### "PACKAGE_NAME" "PACKAGE_VERSION"\n" "###\n" "\n" "###\n" "### lines beginning with a '#' character are comments\n" "###\n" "\n" ); /* Ensure consistent number formatting... */ locale_t loc = newlocale (LC_NUMERIC_MASK, "C", NULL); locale_t baseloc = uselocale (loc); /* We would take the config lock here. But this would cause a lock * inversion with the serializer above and config_AutoSaveConfigFile(). vlc_rwlock_rdlock (&config_lock);*/ /* Look for the selected module, if NULL then save everything */ for (int i = 0; (p_parser = list[i]) != NULL; i++) { module_config_t *p_item, *p_end; if( !p_parser->i_config_items ) continue; fprintf( file, "[%s]", p_parser->psz_object_name ); if( p_parser->psz_longname ) fprintf( file, " # %s\n\n", p_parser->psz_longname ); else fprintf( file, "\n\n" ); for( p_item = p_parser->p_config, p_end = p_item + p_parser->confsize; p_item < p_end; p_item++ ) { if ((p_item->i_type & CONFIG_HINT) /* ignore hint */ || p_item->b_removed /* ignore deprecated option */ || p_item->b_unsaveable) /* ignore volatile option */ continue; if (IsConfigIntegerType (p_item->i_type)) { int64_t val = p_item->value.i; config_Write (file, p_item->psz_text, (p_item->i_type == CONFIG_ITEM_BOOL) ? N_("boolean") : N_("integer"), val == p_item->orig.i, p_item->psz_name, "%"PRId64, val); } else if (IsConfigFloatType (p_item->i_type)) { float val = p_item->value.f; config_Write (file, p_item->psz_text, N_("float"), val == p_item->orig.f, p_item->psz_name, "%f", val); } else { const char *psz_value = p_item->value.psz; bool modified; assert (IsConfigStringType (p_item->i_type)); modified = !!strcmp (psz_value ? psz_value : "", p_item->orig.psz ? p_item->orig.psz : ""); config_Write (file, p_item->psz_text, N_("string"), !modified, p_item->psz_name, "%s", psz_value ? psz_value : ""); } p_item->b_dirty = false; } } vlc_rwlock_unlock (&config_lock); module_list_free (list); if (loc != (locale_t)0) { uselocale (baseloc); freelocale (loc); } /* * Restore old settings from the config in file */ if (bigsize) fwrite (bigbuf, 1, bigsize, file); /* * Flush to disk and replace atomically */ fflush (file); /* Flush from run-time */ if (ferror (file)) { vlc_unlink (temporary); vlc_mutex_unlock (&lock); msg_Err (p_this, "cannot write configuration file"); clearerr (file); goto error; } #if defined(__APPLE__) || defined(__ANDROID__) fsync (fd); /* Flush from OS */ #else fdatasync (fd); /* Flush from OS */ #endif #if defined (WIN32) || defined (__OS2__) /* Windows cannot (re)move open files nor overwrite existing ones */ fclose (file); vlc_unlink (permanent); #endif /* Atomically replace the file... */ if (vlc_rename (temporary, permanent)) vlc_unlink (temporary); /* (...then synchronize the directory, err, TODO...) */ /* ...and finally close the file */ vlc_mutex_unlock (&lock); #if !defined (WIN32) && !defined (__OS2__) fclose (file); #endif free (temporary); free (permanent); free (bigbuf); return 0; error: if( file ) fclose( file ); free (temporary); free (permanent); free (bigbuf); return -1; }
int main(int argc, char **argv) { int pid, fds[2], pid1; char buf[200]; err_setarg0(argv[0]); err_setlogopts(ERR_PID|ERR_MICRO); dump_pgrps(); if (pipe(fds) != 0) err_syserr("failed to create pipe: "); pid = fork(); if (pid == 0) { close(fds[0]); for (int i = 0; i < 3; i++) { printf("Prompt %d: ", i); fflush(0); if (scanf("%199s", buf) != 1) { int errnum = errno; err_remark("Child1:\n"); dump_pgrps(); errno = errnum; err_sysrem("scanf() failed: "); clearerr(stdin); } else { /* Write the null terminator too */ ssize_t rbytes = strlen(buf) + 1; ssize_t wbytes = write(fds[1], buf, rbytes); if (wbytes != rbytes) err_sysrem("short write (read %zu, write %zu)\n", rbytes, wbytes); } sleep(3); } } else { pid1 = fork(); if (pid1 == 0) { close(fds[1]); for (int i = 0; i < 3; i++) { if (read(fds[0], buf, sizeof(buf)) > 0) printf("Input %d: %s\n", i, buf); else { int errnum = errno; err_remark("Child2:\n"); dump_pgrps(); errno = errnum; err_sysrem("read() failed: "); } } } else if (argc > 2) { err_remark("Kids are %d and %d\n", pid, pid1); sleep(5); err_remark("Parent exits\n"); } else if (argc > 1 && argv != 0) // Avoid compilation warning for unused argv { err_remark("Kids are %d and %d\n", pid, pid1); int status; int corpse = wait(&status); err_remark("Parent gets PID %d status 0x%.4X\n", corpse, status); } } return 0; }
static void app_clearerr(FILE *fp) { clearerr(fp); }
int main(int argc, char* argv[]) { int command_file = stdin; int quiet = 0; int r = 0; // initialize zombies struct zombies* z = zombies_alloc(); // Check for '-q' option: be quiet (print no prompts) if (argc > 1 && strcmp(argv[1], "-q") == 0) { quiet = 1; --argc, ++argv; } // Check for filename option: read commands from file if (argc > 1) { command_file = fopen(argv[1], "rb"); if (!command_file) { perror(argv[1]); exit(1); } } char buf[BUFSIZ]; int bufpos = 0; int needprompt = 1; while (!feof(command_file)) { // Print the prompt at the beginning of the line if (needprompt && !quiet) { printf("sh61[%d]$ ", getpid()); fflush(stdout); needprompt = 0; } // Read a string, checking for error or EOF if (fgets(&buf[bufpos], BUFSIZ - bufpos, command_file) == NULL) { if (ferror(command_file) && errno == EINTR) { // ignore EINTR errors clearerr(command_file); buf[bufpos] = 0; } else { if (ferror(command_file)) perror("sh61"); break; } } // If a complete command line has been provided, run it bufpos = strlen(buf); if (bufpos == BUFSIZ - 1 || (bufpos > 0 && buf[bufpos - 1] == '\n')) { eval_command_line(buf, z); bufpos = 0; needprompt = 1; } // kill zombie processes for(int i = 0; i < z->numzombies; ++i) waitpid(z->zombielist[i], NULL, WNOHANG | WUNTRACED); } zombies_free(z); return 0; }
t_stat pt_svc (UNIT *uptr) { int32 c; uint32 cmd; uint32 st; switch (pt_cmd) { /* case on state */ case PTS_INIT: /* I/O init */ st = chan_get_cmd (pt_dib.dva, &cmd); /* get command */ if (CHS_IFERR (st)) /* channel error? */ return pt_chan_err (st); if ((cmd == PTS_WRITE) || /* valid command? */ ((cmd & 0x7F) == PTS_READ)) pt_cmd = cmd; /* next state */ else pt_cmd = PTS_END; /* no, end state */ sim_activate (uptr, chan_ctl_time); /* continue thread */ break; case PTS_READ: case PTS_READI: sim_activate (uptr, uptr->wait); /* continue thread */ if ((uptr->flags & UNIT_ATT) == 0) /* not attached? */ return ptr_stopioe? SCPE_UNATT: SCPE_OK; if ((c = getc (uptr->fileref)) == EOF) { /* read char */ if (feof (uptr->fileref)) { /* end of file? */ chan_set_chf (pt_dib.dva, CHF_LNTE); /* length error */ pt_cmd = PTS_END; /* end state */ break; } else { /* real error */ perror ("PTR I/O error"); clearerr (uptr->fileref); chan_set_chf (pt_dib.dva, CHF_XMDE); /* data error */ return pt_chan_err (SCPE_IOERR); /* force uend */ } } uptr->pos = uptr->pos + 1; if (c != 0) /* leader done? */ ptr_nzc = 1; /* set flag */ if ((pt_cmd == PTS_READI) || ptr_nzc) { st = chan_WrMemB (pt_dib.dva, c); /* write to memory */ if (CHS_IFERR (st)) /* channel error? */ return pt_chan_err (st); if (st == CHS_ZBC) /* bc == 0? */ pt_cmd = PTS_END; /* end state */ } break; case PTS_WRITE: /* write */ sim_activate (uptr, pt_unit[PTP].wait); /* continue thread */ if ((pt_unit[PTP].flags & UNIT_ATT) == 0) /* not attached? */ return ptp_stopioe? SCPE_UNATT: SCPE_OK; st = chan_RdMemB (pt_dib.dva, &c); /* read from channel */ if (CHS_IFERR (st)) /* channel error? */ return pt_chan_err (st); if (putc (c, pt_unit[PTP].fileref) == EOF) { perror ("PTP I/O error"); clearerr (pt_unit[PTP].fileref); chan_set_chf (pt_dib.dva, CHF_XMDE); /* data error */ return pt_chan_err (SCPE_IOERR); /* force uend */ } pt_unit[PTP].pos = pt_unit[PTP].pos + 1; if (st == CHS_ZBC) /* bc == 0? */ pt_cmd = PTS_END; /* end state */ break; case PTS_END: /* command done */ st = chan_end (pt_dib.dva); /* set channel end */ if (CHS_IFERR (st)) /* channel error? */ return pt_chan_err (st); if (st == CHS_CCH) { /* command chain? */ pt_cmd = PTS_INIT; /* restart thread */ sim_activate (uptr, chan_ctl_time); } break; } return SCPE_OK; }
int stail(const char* nomFichier, const unsigned int nbr) { int nbAffichees = nbr; // Indice de parcours int i=0; // Indicateur d'erreur lors du parcours du fichier / sert aussi de code retour int doNotDisplay=0; // Tampon des positions de debut de lignes int *t_positions = malloc(sizeof(int)*100); // Nombre de lignes dans le fichier int nbLignes = 0; // Tampon de la ligne courante char *t_ligne = malloc(sizeof(char)*TAILLE_LIGNE); FILE *pt_fic = fopen(nomFichier, "r"); if(NULL==pt_fic) { printf("Impossible d'ouvrir le fichier %s : (%d) %s\n", nomFichier, errno, strerror(errno)); // On positionne le code retour doNotDisplay=1; } else { // La premiere ligne commence maintenant *(t_positions+i)=ftell(pt_fic); if(1L==*(t_positions+i)) { perror("Erreur lors de la lecture"); doNotDisplay=1; } i+=1; // Flag de lecture int keepReading=1; // Boucler sur le fichier pour determiner les positions des debuts de lignes while( 1 == keepReading ) { // Lecture d'une nouvelle ligne t_ligne = fgets(t_ligne, TAILLE_LIGNE, pt_fic); // On continue a lire ? if(t_ligne==NULL) { // Stopper la lecture keepReading=0; // On determine la cause de l'erreur if(0 != feof(pt_fic)) { // Fin du fichier atteinte //puts("Fichier parcouru avec succes"); } else { // Autre erreur perror("Erreur lors de la lecture"); // On n'affichera pas le fichier doNotDisplay=1; } } else { // Ligne lu en entier ou buffer trop petit ? if(NULL==strrchr(t_ligne, '\n')) { //DEBUG //printf("(%dd)%s", i, t_ligne); // Buffer trop petit pour contenir la ligne entiere : on continue a lire sans memoriser la position } else { //DEBUG //printf("(%d) %s", i, t_ligne); // Memorisation de la position *(t_positions+i)=ftell(pt_fic); if(1L==*(t_positions+i)) { perror("Erreur lors de la lecture"); doNotDisplay=1; } i+=1; } } }//while // -------------------------------------------------------------------------------------------- // Affichage a la facon de tail si pas d'erreur lors du parcours if (1!=doNotDisplay) { // Tampon de lecture char carac=0; // Nombre de lignes nbLignes = i-1; //printf("\n\nOn finit de lire le fichier. Il y a %d lignes.\nOn va maintenant afficher la fin du fichier, soit les %d dernieres lignes.\n\n", nbLignes, nbAffichees); // Enlever le flag de fin de fichier clearerr(pt_fic); // Se positionner au bon endroit if(nbLignes>nbAffichees) { fseek(pt_fic, *(t_positions+nbLignes-nbAffichees), SEEK_SET); } else { fseek(pt_fic, *(t_positions), SEEK_SET); } // Affichage while ( EOF!=(carac=fgetc(pt_fic)) ) { putchar(carac); } } // Fermeture du fichier fclose(pt_fic); }//Ouverture du fichier return doNotDisplay; }//stail