Example #1
0
void PrintTime(){
    time(&rawtime);
    timeinfo = localtime(&rawtime);
    strftime(time_buffer,64,"%x %H:%M:%S",timeinfo);//"%a %b %d %Y %X %z",timeinfo);
    printf(time_buffer);
}
Example #2
0
HeapString DateTime::ToString(const StringRef& formaterStr) const
{
	char s[256];
	strftime(s, sizeof(s), formaterStr.c_str(), &mDate);
	return HeapString(s);
}
Example #3
0
static BDMDExamineData* get_examine_data_from_table (GHashTable *table, gboolean free_table, GError **error) {
    BDMDExamineData *data = g_new0 (BDMDExamineData, 1);
    gchar *value = NULL;
    gchar *first_space = NULL;
    BSSize size = NULL;
    BSError *bs_error = NULL;
    struct tm tm;
    char time_str[20];
    gchar *name_str = NULL;

    data->level = g_strdup ((gchar*) g_hash_table_lookup (table, "Raid Level"));
    if (!(data->level))
        /* BUG: mdadm outputs "RAID Level" for some metadata formats (rhbz#1380034) */
        data->level = g_strdup ((gchar*) g_hash_table_lookup (table, "RAID Level"));

    value = (gchar*) g_hash_table_lookup (table, "Raid Devices");
    if (!value)
        /* BUG: mdadm outputs "RAID Devices" for some metadata formats (rhbz#1380034) */
        value = (gchar*) g_hash_table_lookup (table, "RAID Devices");
    if (value)
        data->num_devices = g_ascii_strtoull (value, NULL, 0);
    else
        data->num_devices = 0;

    name_str = ((gchar*) g_hash_table_lookup (table, "Name"));
    if (name_str) {
        g_strstrip (name_str);
        first_space = strchr (name_str, ' ');
        if (first_space)
            *first_space = '\0';
        data->name = g_strdup (name_str);
    }

    value = (gchar*) g_hash_table_lookup (table, "Array Size");
    if (value) {
        first_space = strchr (value, ' ');
        if (first_space)
            *first_space = '\0';
        if (value && first_space)
            /* Array Size is in KiB */
            data->size = g_ascii_strtoull (value, NULL, 0) * 1024;
    } else
        data->size = 0;

    data->uuid = g_strdup ((gchar*) g_hash_table_lookup (table, "Array UUID"));
    if (!data->uuid)
        /* also try just "UUID" which may be reported e.g for IMSM FW RAID */
        data->uuid = g_strdup ((gchar*) g_hash_table_lookup (table, "UUID"));

    value = (gchar*) g_hash_table_lookup (table, "Update Time");
    if (value) {
        memset(&tm, 0, sizeof(struct tm));
        strptime(value, "%a %b %e %H:%M:%S %Y", &tm);
        strftime(time_str, sizeof(time_str), "%s" , &tm);

        data->update_time = g_ascii_strtoull (time_str, NULL, 0);
    } else
        data->update_time = 0;

    data->dev_uuid = g_strdup ((gchar*) g_hash_table_lookup (table, "Device UUID"));

    value = (gchar*) g_hash_table_lookup (table, "Events");
    if (value)
        data->events = g_ascii_strtoull (value, NULL, 0);
    else
        data->events = 0;

    value = (gchar*) g_hash_table_lookup (table, "Version");
    if (value)
        data->metadata = g_strdup (value);
    else
        data->metadata = NULL;

    value = (gchar*) g_hash_table_lookup (table, "Chunk Size");
    if (value) {
        size = bs_size_new_from_str (value, &bs_error);
        if (size) {
            data->chunk_size = bs_size_get_bytes (size, NULL, &bs_error);
            bs_size_free (size);
        }

        if (bs_error) {
            g_set_error (error, BD_MD_ERROR, BD_MD_ERROR_PARSE,
                         "Failed to parse chunk size from mdexamine data: %s", bs_error->msg);
            bs_clear_error (&bs_error);
        }
    } else
        data->chunk_size = 0;

    if (free_table)
        g_hash_table_destroy (table);

    return data;
}
Example #4
0
File: x.c Project: childhood/parcle
/* Here is the deal, we read as much as we can into the empty buffer, then
 * reset the buffer pointer to the end of the read material and append at
 * next read
 */
void
read_request( struct cn_strct *cn )
{
	char *next;
	int   num_recv;

	time_t     now = time(NULL);
	struct tm *tm_struct;


	/* FIXME: For now assume that RECV_BUFF_LENGTH is enough for one read */
	num_recv = recv(
		cn->net_socket,
		cn->data_buf,
		RECV_BUFF_LENGTH - cn->processed_bytes,
		//MAX_READ_LENGTH,
		0
	);

	// sanity check
	if (num_recv <= 0) {
		if (num_recv <= 0)         /* really dead? */
			remove_conn_from_list(cn);
		return;
	}

	// set the read pointer to where we left off
	next = cn->data_buf_head + cn->processed_bytes;

	// adjust buffer
	cn->processed_bytes += num_recv;
	cn->data_buf = cn->data_buf_head + cn->processed_bytes;

	/* null terminate the current buffer -> overwrite on next read */
	cn->data_buf_head[cn->processed_bytes] = '\0';

	/* a naive little line parser */
	while ( (*next != '\0') ) {
		if ( *(next)=='\r')
			if (*(next+1)=='\n' &&
			    *(next+2)=='\r' && *(next+3)=='\n' ) {
			/* proceed next stage
			   prepare the global date string */
				if (now-_Last_loop>0) {
					_Last_loop = now;
					tm_struct = gmtime(&_Last_loop);
					//Sun, 06 Nov 1994 08:49:37 GMT
					strftime( _Master_date, 30, "%a, %d %b %Y %H:%M:%S %Z", tm_struct);
				}
				cn->req_state = REQSTATE_BUFF_HEAD;

				/* enqueue this connection to the _App_queue */
				pthread_mutex_lock( &pull_job_mutex );
				if (NULL == _Queue_tail) {
					_Queue_tail = _Queue_head = cn;
					_Queue_count = 1;
				}
				else {
					_Queue_tail->q_prev = cn;
					_Queue_tail = cn;
					_Queue_count++;
				}
				pthread_mutex_unlock( &pull_job_mutex );

				/* wake a worker to start the application */
				pthread_cond_signal (&wake_worker_cond);
			}

		next++;
	}
}
Example #5
0
/**
 * @short Transforms a time_t to a RFC 822 date string
 * 
 * This date format is the standard in HTTP protocol as RFC 2616, section 3.3.1
 * 
 * The dest pointer must be at least 32 bytes long as thats the maximum size of the date.
 */
void onion_shortcut_date_string(time_t t, char *dest){
	struct tm ts;
	gmtime_r(&t, &ts);
	strftime(dest, t, "%a, %d %b %Y %T %Z", &ts);
}
Example #6
0
// Credit to NTAuthority
LONG WINAPI DumpHandler::CustomUnhandledExceptionFilter(LPEXCEPTION_POINTERS ExceptionInfo)
{
	// Ignore breakpoints.
	if (ExceptionInfo->ExceptionRecord->ExceptionCode == EXCEPTION_BREAKPOINT) return EXCEPTION_CONTINUE_EXECUTION;

	// Try skipping exceptions
	/* Disable that, it seems unsafe
	if ((ExceptionInfo->ExceptionRecord->ExceptionFlags & EXCEPTION_NONCONTINUABLE) != EXCEPTION_NONCONTINUABLE)
	{
		OutputDebugStringA(hString::va("New exception at 0x%X, try ignoring it...", ExceptionInfo->ExceptionRecord->ExceptionAddress));
		ExceptionInfo->ExceptionRecord->ExceptionFlags |= EXCEPTION_NONCONTINUABLE;
		return EXCEPTION_CONTINUE_EXECUTION;
	}
	else
	{
		OutputDebugStringA("Ignoring failed. Handling it now...");
	}
	*/

	// step 1: write minidump
	char error[1024];
	char filename[MAX_PATH];
	__time64_t time;
	tm* ltime;

	_time64(&time);
	ltime = _localtime64(&time);
	strftime(filename, sizeof(filename) - 1, "Redacted - %H-%M-%S %d.%m.%Y.dmp", ltime);
	_snprintf(error, sizeof(error) - 1, "A minidump has been written to %s.", filename);

	HANDLE hFile = CreateFile(filename, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

	if (hFile != INVALID_HANDLE_VALUE)
	{
		MINIDUMP_EXCEPTION_INFORMATION ex = { 0 };
		ex.ThreadId = GetCurrentThreadId();
		ex.ExceptionPointers = ExceptionInfo;
		ex.ClientPointers = FALSE;

		MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hFile, MiniDumpNormal, &ex, NULL, NULL);

		CloseHandle(hFile);
	}
	else
	{
		_snprintf(error, sizeof(error) - 1, "An error (0x%x) occurred during creating %s.", GetLastError(), filename);
	}

	// step 2: exit the application
	// why was this removed?
	if (ExceptionInfo->ExceptionRecord->ExceptionCode == EXCEPTION_STACK_OVERFLOW)
	{
		MessageBox(0, "Termination because of a stack overflow.", "ERROR", MB_ICONERROR);
	}
	else
	{
		MessageBox(0, hString::va("Fatal error (0x%08x) at 0x%08x.\n%s", ExceptionInfo->ExceptionRecord->ExceptionCode, ExceptionInfo->ExceptionRecord->ExceptionAddress, error), "ERROR", MB_ICONERROR);
	}

	TerminateProcess(GetCurrentProcess(), ExceptionInfo->ExceptionRecord->ExceptionCode);
	return 0;
}
Example #7
0
/**
 * @brief Start the storage server.
 *
 * This is the main entry point for the storage server.  It reads the
 * configuration file, starts listening on a port, and proccesses
 * commands from clients.
 */
int main(int argc, char *argv[])
{


	Table database[MAX_DATABASE_LEN];

	//printf("Setting time\n");//remove
	  time ( &rawtime );
	  timeinfo2 = localtime ( &rawtime );
	  //printf("Finished rawtime stuff\n"); //remove

	  //printf("About to do strftime\n"); //remove
	  strftime (buffer2,40,"Server-%Y-%m-%d-%H-%M-%S.log",timeinfo2);
	  puts (buffer2);
	  //printf("Finished setting time\n");//remove

	// Process command line arguments.
	// This program expects exactly one argument: the config file name.
	assert(argc > 0);
	if (argc != 2) {
		printf("Usage %s <config_file>\n", argv[0]);
		exit(EXIT_FAILURE);
	}
	char *config_file = argv[1];

	// Read the config file.
	struct config_params params;
	int status = read_config(config_file, &params);
	if (status != 0) {
		printf("Error processing config file.\n");
		exit(EXIT_FAILURE);
	}

	n = sprintf(message, "Server on %s:%d\n", params.server_host, params.server_port);
	//printf("%i", n);
	fp = fopen(buffer2, "a+");
	logger(LOGGING, fp, message);
	fclose(fp);

	// Create a socket.
	int listensock = socket(PF_INET, SOCK_STREAM, 0);
	if (listensock < 0) {
		printf("Error creating socket.\n");
		exit(EXIT_FAILURE);
	}

	// Allow listening port to be reused if defunct.
	int yes = 1;
	status = setsockopt(listensock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof yes);
	if (status != 0) {
		printf("Error configuring socket.\n");
		exit(EXIT_FAILURE);
	}

	// Bind it to the listening port.
	struct sockaddr_in listenaddr;
	memset(&listenaddr, 0, sizeof listenaddr);
	listenaddr.sin_family = AF_INET;
	listenaddr.sin_port = htons(params.server_port);
	inet_pton(AF_INET, params.server_host, &(listenaddr.sin_addr)); // bind to local IP address
	status = bind(listensock, (struct sockaddr*) &listenaddr, sizeof listenaddr);
	if (status != 0) {
		printf("Error binding socket.\n");
		exit(EXIT_FAILURE);
	}

	// Listen for connections.
	status = listen(listensock, MAX_LISTENQUEUELEN);
	if (status != 0) {
		printf("Error listening on socket.\n");
		exit(EXIT_FAILURE);
	}

	// Listen loop.
	int wait_for_connections = 1;
	while (wait_for_connections) {
		// Wait for a connection.
		struct sockaddr_in clientaddr;
		socklen_t clientaddrlen = sizeof clientaddr;
		int clientsock = accept(listensock, (struct sockaddr*)&clientaddr, &clientaddrlen);
		if (clientsock < 0) {
			printf("Error accepting a connection.\n");
			exit(EXIT_FAILURE);
		}
		n = sprintf(message, "Got a connection from %s:%d.\n", inet_ntoa(clientaddr.sin_addr), clientaddr.sin_port);
		fp = fopen(buffer2, "a+");
		logger(LOGGING, fp, message);
		fclose(fp);

		// Get commands from client.
		int wait_for_commands = 1;
		do {
			// Read a line from the client.
			char cmd[MAX_CMD_LEN];
			int status = recvline(clientsock, cmd, MAX_CMD_LEN);
			if (status != 0) {
				// Either an error occurred or the client closed the connection.
				wait_for_commands = 0;
			} else {
				// Handle the command from the client.
				int status = handle_command(clientsock, cmd, database, params.username, params.password);
				if (status != 0)
					wait_for_commands = 0; // Oops.  An error occured.
			}
		} while (wait_for_commands);

		// Close the connection with the client.
		close(clientsock);
		n = sprintf(message, "Closed connection from %s:%d.\n", inet_ntoa(clientaddr.sin_addr), clientaddr.sin_port);
		fp = fopen(buffer2, "a+");
		logger(LOGGING, fp, message);
		fclose(fp);
	}

	// Stop listening for connections.
	close(listensock);

	return EXIT_SUCCESS;
}
Example #8
0
static void calculate_speed(struct progress_bar *prog, unsigned long long copied, unsigned long long current, int done, prog_stat_t *prog_stat){
    char *format = "%H:%M:%S";
    uint64_t speedps = 1;
    uint64_t speed = 1;
    double dspeed = 1.0;
    float percent = 1.0;
    time_t remained;
    time_t elapsed;
    char Rformated[12], Eformated[12];
    char speed_unit[] = "    ";
    struct tm *Rtm, *Etm;
    uint64_t gbyte=1000000000.0;
    uint64_t mbyte=1000000;
    uint64_t kbyte=1000;


    percent  = prog->unit * copied;
    if (percent <= 0)
	percent = 1;
    else if (percent >= 100)
	percent = 99.99;

    elapsed  = (time(0) - prog->initial_time);
    if (elapsed <= 0)
	elapsed = 1;

    speedps  = prog->block_size * copied / elapsed;
    speed = speedps * 60.0;

    prog_stat->percent   = percent;

    if (speed >= gbyte){
	dspeed = (double)speed / (double)gbyte;
	strncpy(speed_unit, "GB", 3);
	strncpy(prog_stat->speed_unit, speed_unit, 3);
    }else if (speed >= mbyte){
	dspeed = (double)speed / (double)mbyte;
	strncpy(speed_unit, "MB", 3);
	strncpy(prog_stat->speed_unit, speed_unit, 3);
    }else if (speed >= kbyte){
	dspeed = (double)speed / (double)kbyte;
	strncpy(speed_unit, "KB", 3);
	strncpy(prog_stat->speed_unit, speed_unit, 3);
    }else{
	dspeed = speed;
	strncpy(speed_unit, "byte", 5);
	strncpy(prog_stat->speed_unit, speed_unit, 5);
    }

    prog_stat->total_percent = prog->total_unit * current;

    prog_stat->speed     = dspeed;

    if (done != 1){
        remained = (time_t)((elapsed/percent*100) - elapsed);

	if ((unsigned int)remained > 86400){
	    snprintf(Rformated, sizeof(Rformated), " > %3i hrs ", ((int)remained/3600));
	}else{
	    Rtm = gmtime(&remained);
	    strftime(Rformated, sizeof(Rformated), format, Rtm);
	}

	if ((unsigned int)elapsed > 86400){
	    snprintf(Eformated, sizeof(Eformated), " > %3i hrs ", ((int)elapsed/3600));
	}else{
	    Etm = gmtime(&elapsed);
	    strftime(Eformated, sizeof(Eformated), format, Etm);
	}

    } else {
        prog_stat->percent=100;
        remained = (time_t)0;
        Rtm = gmtime(&remained);
	strftime(Rformated, sizeof(Rformated), format, Rtm);

	if ((unsigned int)elapsed > 86400){
	    snprintf(Eformated, sizeof(Eformated), " > %3i hrs ", ((int)elapsed/3600));
	}else{
	    Etm = gmtime(&elapsed);
	    strftime(Eformated, sizeof(Eformated), format, Etm);
	}
    }

    strncpy(prog_stat->Eformated, Eformated, sizeof(prog_stat->Eformated));
    strncpy(prog_stat->Rformated, Rformated, sizeof(prog_stat->Rformated));
}
Example #9
0
void bsodFatal(const char *component)
{
	/* show no more than one bsod while shutting down/crashing */
	if (bsodhandled) return;
	bsodhandled = true;

	std::string lines = getLogBuffer();

		/* find python-tracebacks, and extract "  File "-strings */
	size_t start = 0;

	std::string crash_emailaddr = CRASH_EMAILADDR;
	std::string crash_component = "enigma2";

	if (component)
		crash_component = component;
	else
	{
		while ((start = lines.find("\n  File \"", start)) != std::string::npos)
		{
			start += 9;
			size_t end = lines.find("\"", start);
			if (end == std::string::npos)
				break;
			end = lines.rfind("/", end);
				/* skip a potential prefix to the path */
			unsigned int path_prefix = lines.find("/usr/", start);
			if (path_prefix != std::string::npos && path_prefix < end)
				start = path_prefix;

			if (end == std::string::npos)
				break;

			std::string filename(lines.substr(start, end - start) + INFOFILE);
			std::ifstream in(filename.c_str());
			if (in.good()) {
				std::getline(in, crash_emailaddr) && std::getline(in, crash_component);
				in.close();
			}
		}
	}

	FILE *f;
	std::string crashlog_name;
	std::ostringstream os;
	os << "/media/hdd/enigma2_crash_";
	os << time(0);
	os << ".log";
	crashlog_name = os.str();
	f = fopen(crashlog_name.c_str(), "wb");

	if (f == NULL)
	{
		/* No hardisk. If there is a crash log in /home/root, leave it
		 * alone because we may be in a crash loop and writing this file
		 * all night long may damage the flash. Also, usually the first
		 * crash log is the most interesting one. */
		crashlog_name = "/home/root/enigma2_crash.log";
		if ((access(crashlog_name.c_str(), F_OK) == 0) ||
		    ((f = fopen(crashlog_name.c_str(), "wb")) == NULL))
		{
			/* Re-write the same file in /tmp/ because it's expected to
			 * be in RAM. So the first crash log will end up in /home
			 * and the last in /tmp */
			crashlog_name = "/tmp/enigma2_crash.log";
			f = fopen(crashlog_name.c_str(), "wb");
		}
	}

	if (f)
	{
		time_t t = time(0);
		struct tm tm;
		char tm_str[32];

		localtime_r(&t, &tm);
		strftime(tm_str, sizeof(tm_str), "%a %b %_d %T %Y", &tm);

		XmlGenerator xml(f);

		xml.open("BlakHole");

		xml.open("enigma2");
		xml.string("crashdate", tm_str);
		xml.string("compiledate", __DATE__);
		xml.string("contactemail", crash_emailaddr);
		xml.comment("Please email this crashlog to above address");

		xml.string("skin", getConfigString("config.skin.primary_skin", "Default Skin"));
		xml.string("sourcedate", enigma2_date);
		xml.string("branch", enigma2_branch);
		xml.string("rev", enigma2_rev);
		xml.string("version", PACKAGE_VERSION);
		xml.close();

		xml.open("image");
		if(access("/proc/stb/info/boxtype", F_OK) != -1) {
			xml.stringFromFile("stbmodel", "/proc/stb/info/boxtype");
		}
		else if (access("/proc/stb/info/vumodel", F_OK) != -1) {
			xml.stringFromFile("stbmodel", "/proc/stb/info/vumodel");
		}
		else if (access("/proc/stb/info/model", F_OK) != -1) {
			xml.stringFromFile("stbmodel", "/proc/stb/info/model");
		}
		xml.cDataFromCmd("kernelversion", "uname -a");
		xml.stringFromFile("kernelcmdline", "/proc/cmdline");
		xml.stringFromFile("nimsockets", "/proc/bus/nim_sockets");
		xml.cDataFromFile("imageversion", "/etc/image-version");
		xml.cDataFromFile("imageissue", "/etc/issue.net");
		xml.close();

		xml.open("crashlogs");
		xml.cDataFromString("enigma2crashlog", getLogBuffer());
		xml.close();

		xml.close();

		fclose(f);
	}

	ePtr<gMainDC> my_dc;
	gMainDC::getInstance(my_dc);

	gPainter p(my_dc);
	p.resetOffset();
	p.resetClip(eRect(ePoint(0, 0), my_dc->size()));
	p.setBackgroundColor(gRGB(0x008000));
	p.setForegroundColor(gRGB(0xFFFFFF));

	int hd =  my_dc->size().width() == 1920;
	ePtr<gFont> font = new gFont("Regular", hd ? 30 : 20);
	p.setFont(font);
	p.clear();

	eRect usable_area = eRect(hd ? 30 : 100, hd ? 30 : 70, my_dc->size().width() - (hd ? 60 : 150), hd ? 150 : 100);

	os.str("");
	os.clear();
	os << "We are really sorry. Your STB encountered "
		"a software problem, and needs to be restarted.\n"
		"Please send the logfile " << crashlog_name << " to " << crash_emailaddr << ".\n"
		"Your STB restarts in 10 seconds!\n"
		"Component: " << crash_component;

	p.renderText(usable_area, os.str().c_str(), gPainter::RT_WRAP|gPainter::RT_HALIGN_LEFT);

	usable_area = eRect(hd ? 30 : 100, hd ? 180 : 170, my_dc->size().width() - (hd ? 60 : 180), my_dc->size().height() - (hd ? 30 : 20));

	int i;

	start = std::string::npos + 1;
	for (i=0; i<20; ++i)
	{
		start = lines.rfind('\n', start - 1);
		if (start == std::string::npos)
		{
			start = 0;
			break;
		}
	}

	font = new gFont("Regular", hd ? 21 : 14);
	p.setFont(font);

	p.renderText(usable_area,
		lines.substr(start), gPainter::RT_HALIGN_LEFT);
	sleep(10);

	/*
	 * When 'component' is NULL, we are called because of a python exception.
	 * In that case, we'd prefer to to a clean shutdown of the C++ objects,
	 * and this should be safe, because the crash did not occur in the
	 * C++ part.
	 * However, when we got here for some other reason, a segfault probably,
	 * we prefer to stop immediately instead of performing a clean shutdown.
	 * We'd risk destroying things with every additional instruction we're
	 * executing here.
	 */
	if (component) raise(SIGKILL);
}
void date_time_layer_format_time(
    char* buffer, size_t buffer_length, struct tm* now, bool is_24h
) {
    strftime(buffer, buffer_length, is_24h ? "%H:%M" : "%I:%M", now);
}
Example #11
0
int main(int argc, char** argv){
	int quadrant_line, quadrant_column;
	
	char *videoFileName = argv[1];
	char quadFileName[64];

	int i = 0, k, j;

	long unsigned int inc = 0;
	long unsigned int incaudio = 0;

	int videoStreamIndex;
	int audioStreamIndex= -1;
	int frameFinished, gotPacket;

	AVDictionary	*codecOptions = NULL;
	
	UDP_PTSframe_t PTS_frame;

	struct tm *start_time_tm;
	char start_time_str[64];
	long unsigned int start_time;
	time_t start_timer_t;
	
	//Crop env
	int tam_quad;
	int frist = 1, marginLeft = 0, marginTop = 0;
	int width , height;

    if(argc < 4){
        usage();    
        return -1;
    }

    signal (SIGTERM, handlerToFinish);
	signal (SIGINT, handlerToFinish);

    tam_quad = sqrt(amount_of_quadrants);
    quadrant_line = atoi(argv[2]);
    quadrant_column = atoi(argv[3]);
    amount_of_quadrants = (quadrant_line * quadrant_column) + 1;

    strcpy (quadFileName, argv[4]);

    //Allocat output streams context
    ff_output = malloc (sizeof(ff_output_t) * amount_of_quadrants);

	av_register_all();
	avformat_network_init();

	//Initialize Input
	if (avformat_open_input (&ff_input.formatCtx, videoFileName, NULL, NULL) != 0) {
		printf ("Cold not open input video file at %s\n", videoFileName);
		return -1;
	}

	if (avformat_find_stream_info(ff_input.formatCtx, NULL) < 0) {
		printf ("Cold not get stream info\n");
		return -1;
	}

	av_dump_format(ff_input.formatCtx, 0, videoFileName, 0);

	videoStreamIndex = av_find_best_stream(ff_input.formatCtx, AVMEDIA_TYPE_VIDEO, -1, -1, &ff_input.encoder, 0);
	if (videoStreamIndex < 0) {
		printf ("no video streams found\n");
		return -1;
	}

	audioStreamIndex = av_find_best_stream(ff_input.formatCtx, AVMEDIA_TYPE_AUDIO, -1, -1, &ff_input.audioencoder, 0);
    if (audioStreamIndex < 0) {
        printf ("no audio streams found\n");
        return -1;
    }
    printf ("VIDEO ST %d, AUDIO ST %d\n", videoStreamIndex, audioStreamIndex);

    ff_input.audiocodecCtx = ff_input.formatCtx->streams[audioStreamIndex]->codec;
	ff_input.codecCtx = ff_input.formatCtx->streams[videoStreamIndex]->codec;

	if (avcodec_open2 (ff_input.audiocodecCtx, ff_input.audioencoder, NULL) < 0) {
        printf ("Could not open input codec\n");
        return -1;
    }

	if (avcodec_open2 (ff_input.codecCtx, ff_input.encoder, NULL) < 0) {
		printf ("Could not open input codec\n");
		return -1;
	}

	//Get system time and append as metadata
	getSystemTime (&PTS_frame.frameTimeVal); //Must be the same for all output contexts
	start_time = PTS_frame.frameTimeVal.tv_sec;
	start_timer_t = (time_t) start_time;
	start_time_tm = localtime (&start_timer_t);
	strftime(start_time_str, sizeof start_time_str, "%Y-%m-%d %H:%M:%S", start_time_tm);

	if (avformat_alloc_output_context2(&formatCtx, NULL, AV_OUTPUT_FORMAT, quadFileName) < 0) {
			printf ("could not create output context\n");
			return -1;
	}

	//Initialize Video Output Streams
	for (i = 0; i < amount_of_quadrants - 1; i++) {

		ff_output[i].outStream = avformat_new_stream (formatCtx, NULL);
		if (ff_output[i].outStream == NULL) {
			printf ("Could not create output stream\n");
			return -1;
		}

		ff_output[i].outStream->id = formatCtx->nb_streams - 1;

		ff_output[i].codecCtx = ff_output[i].outStream->codec;
		ff_output[i].encoder = avcodec_find_encoder_by_name (AV_OUTPUT_CODEC);
		if (ff_output[i].encoder == NULL) {
			printf ("Codec %s not found..\n", AV_OUTPUT_CODEC);
			return -1;
		}

		//Sliced sizes
		width = ff_input.codecCtx->width/quadrant_column;
		height = ff_input.codecCtx->height/quadrant_line;

		ff_output[i].codecCtx->codec_type 	= AVMEDIA_TYPE_VIDEO;
		ff_output[i].codecCtx->height 		= height;
		ff_output[i].codecCtx->width 		= width;
		ff_output[i].codecCtx->pix_fmt		= ff_input.codecCtx->pix_fmt;

		if (strcmp (AV_OUTPUT_CODEC, "libvpx") == 0) {
			//Maintain input aspect ratio for codec and stream info, and b_frames for codec info
			ff_output[i].codecCtx->sample_aspect_ratio = ff_input.codecCtx->sample_aspect_ratio;
			ff_output[i].codecCtx->max_b_frames = ff_input.codecCtx->max_b_frames;
			ff_output[i].outStream->sample_aspect_ratio = ff_output[i].codecCtx->sample_aspect_ratio;

			//Set custom BIT RATE and THREADs 
			ff_output[i].codecCtx->bit_rate 	= AV_OUTPUT_BITRATE;
			ff_output[i].codecCtx->thread_count = AV_OUTPUT_THREADS;
			ff_output[i].codecCtx->thread_type  = AV_OUTPUT_THREAD_TYPE;

			//Set custo timebase for codec and streams
			ff_output[i].codecCtx->time_base.num = 1;
			ff_output[i].codecCtx->time_base.den = AV_FRAMERATE;
			ff_output[i].outStream->time_base.num = 1;
			ff_output[i].outStream->time_base.den = 10000;			
		}

		if (strcmp (AV_OUTPUT_CODEC, "libx264") == 0) {
			// ff_output[i].codecCtx->profile = FF_PROFILE_H264_MAIN;
			// av_dict_set(&codecOptions, "profile","main",0);

			//Set custom BIT RATE and THREADs 
			ff_output[i].codecCtx->bit_rate 	= AV_OUTPUT_BITRATE;
			ff_output[i].codecCtx->thread_count = AV_OUTPUT_THREADS;
			ff_output[i].codecCtx->thread_type  = AV_OUTPUT_THREAD_TYPE;

			ff_output[i].codecCtx->bit_rate_tolerance = 0;
			ff_output[i].codecCtx->rc_max_rate = 0;
			ff_output[i].codecCtx->rc_buffer_size = 0;
			ff_output[i].codecCtx->gop_size = 40;
			ff_output[i].codecCtx->max_b_frames = 3;
			ff_output[i].codecCtx->b_frame_strategy = 1;
			ff_output[i].codecCtx->coder_type = 1;
			ff_output[i].codecCtx->me_cmp = 1;
			ff_output[i].codecCtx->me_range = 16;
			ff_output[i].codecCtx->qmin = 10;
			ff_output[i].codecCtx->qmax = 51;
			ff_output[i].codecCtx->scenechange_threshold = 40;
			ff_output[i].codecCtx->flags |= CODEC_FLAG_LOOP_FILTER;
			ff_output[i].codecCtx->me_method = ME_HEX;
			ff_output[i].codecCtx->me_subpel_quality = 5;
			ff_output[i].codecCtx->i_quant_factor = 0.71;
			ff_output[i].codecCtx->qcompress = 0.6;
			ff_output[i].codecCtx->max_qdiff = 4;

			//Set custo timebase for codec and streams
			ff_output[i].codecCtx->time_base.num = 1;
			ff_output[i].codecCtx->time_base.den = 24;
			ff_output[i].outStream->time_base.num = 1;
			ff_output[i].outStream->time_base.den = 90000;		
		}

		formatCtx->start_time_realtime = start_time;
		av_dict_set (&formatCtx->metadata, "service_name", start_time_str, 0);
		av_dict_set (&formatCtx->metadata, "creation_time", start_time_str, 0);

		//Open codec
		if (avcodec_open2(ff_output[i].codecCtx, ff_output[i].encoder, &codecOptions)) {
			printf ("Could not open output codec...\n");
			return -1;
		}
	}

	//Initializing Audio Output
	i = amount_of_quadrants-1; //Last stream
	ff_output[i].outStream = avformat_new_stream (formatCtx, NULL);
	if (ff_output[i].outStream == NULL) {
		printf ("Could not create output stream\n");
		return -1;
	}

	ff_output[i].outStream->id = formatCtx->nb_streams - 1;

	ff_output[i].codecCtx = ff_output[i].outStream->codec;
	ff_output[i].encoder = avcodec_find_encoder (ff_input.audiocodecCtx->codec_id);
	if (ff_output[i].encoder == NULL) {
		printf ("Codec %s not found..\n", AUDIO_OUTPUT_CODEC);
		return -1;
	}
  
    ff_output[i].codecCtx = ff_output[amount_of_quadrants-1].outStream->codec;
    ff_output[i].codecCtx->codec_id = ff_input.audiocodecCtx->codec_id;
    ff_output[i].codecCtx->codec_type = AVMEDIA_TYPE_AUDIO;
    ff_output[i].codecCtx->sample_fmt = ff_input.audiocodecCtx->sample_fmt;
    ff_output[i].codecCtx->sample_rate = ff_input.audiocodecCtx->sample_rate;
    ff_output[i].codecCtx->channel_layout = ff_input.audiocodecCtx->channel_layout;
    ff_output[i].codecCtx->channels = av_get_channel_layout_nb_channels(ff_output[amount_of_quadrants-1].codecCtx->channel_layout);
    ff_output[i].codecCtx->bit_rate = ff_input.audiocodecCtx->bit_rate;  
    ff_output[i].codecCtx->sample_aspect_ratio = ff_input.audiocodecCtx->sample_aspect_ratio;
    ff_output[i].codecCtx->max_b_frames = ff_input.audiocodecCtx->max_b_frames;
    ff_output[i].outStream->sample_aspect_ratio = ff_output[i].codecCtx->sample_aspect_ratio;

    ff_output[i].outStream->time_base.num = ff_input.formatCtx->streams[audioStreamIndex]->time_base.num;
	ff_output[i].outStream->time_base.den = ff_input.formatCtx->streams[audioStreamIndex]->time_base.den;

	ff_output[i].codecCtx->time_base.num = ff_input.audiocodecCtx->time_base.num;
	ff_output[i].codecCtx->time_base.den = ff_input.audiocodecCtx->time_base.den;

	printf("sample_rate %d\n", ff_input.audiocodecCtx->sample_rate);

	//Open codec
	if (avcodec_open2(ff_output[i].codecCtx, ff_output[i].encoder, &codecOptions)) {
		printf ("Could not open output codec...\n");
		return -1;
	}

	av_dump_format (formatCtx, 0, quadFileName, 1);

	//Open output context
	if (avio_open (&formatCtx->pb, quadFileName, AVIO_FLAG_WRITE)) {
		printf ("avio_open failed %s\n", quadFileName);
		return -1;
	}
	
	//Write format context header
	if (avformat_write_header (formatCtx, &formatCtx->metadata)) {
		printf ("fail to write outstream header\n");
		return -1;
	}

	printf ("OUTPUT TO %s, at %lu\n", quadFileName, start_time);


	incaudio = 0;
	printf("Generating video streams...\n");
	while(av_read_frame (ff_input.formatCtx, &ff_input.packet) >= 0 && _keepEncoder) {
		if (ff_input.packet.stream_index == audioStreamIndex)
		{
			av_packet_ref  (&ff_output[amount_of_quadrants-1].packet, &ff_input.packet); 
            ff_output[amount_of_quadrants-1].packet.stream_index = amount_of_quadrants-1;
            ff_output[amount_of_quadrants-1].packet.pts = incaudio;

            // printf("%lu\n", ff_output[amount_of_quadrants-1].packet.pts);
            // if(gotPacket){
            	if (av_write_frame(formatCtx, &ff_output[amount_of_quadrants-1].packet) < 0) {
	                printf ("Unable to write to output stream..\n");
	                pthread_exit(NULL);
            	// }
            }            
            incaudio += 2880;
		}

		if (ff_input.packet.stream_index == videoStreamIndex) {

			ff_input.frame = av_frame_alloc();
			avcodec_decode_video2 (ff_input.codecCtx, ff_input.frame, &frameFinished, &ff_input.packet);

			if (frameFinished) {
				//TODO: Slice inputFrame and fill avQuadFrames[quadrant]
				//By now, inputFrame are replicated to all quadrants

				ff_input.frame->pts = av_frame_get_best_effort_timestamp (ff_input.frame);
				
				i = 0;
				for ( k = 0; k < quadrant_line; ++k) {
                    for (j = 0; j < quadrant_column; ++j) {
            			ff_output[i].frame = av_frame_alloc();

            			//make the cut quadrant ff_output[i]!
            			av_picture_crop((AVPicture *)ff_output[i].frame, (AVPicture *)ff_input.frame,       
            							ff_input.formatCtx->streams[videoStreamIndex]->codec->pix_fmt, marginTop, marginLeft);
            			
            			ff_output[i].frame->width = width; // updates the new width
						ff_output[i].frame->height = height; // updates the new height
						ff_output[i].frame->format = ff_input.frame->format;

						ff_output[i].frame->pts = inc;

						ff_output[i].packet.data = NULL;
						ff_output[i].packet.size = 0;
						av_init_packet (&ff_output[i].packet);

						avcodec_encode_video2 (ff_output[i].codecCtx, &ff_output[i].packet, ff_output[i].frame, &gotPacket);

						if (gotPacket) {
							ff_output[i].packet.stream_index = i;
							av_packet_rescale_ts (&ff_output[i].packet,
													ff_output[i].codecCtx->time_base,
													ff_output[i].outStream->time_base);

							if (av_write_frame (formatCtx, &ff_output[i].packet) < 0) {
								printf ("Unable to write to output stream..\n");
								pthread_exit(NULL);
							}

						}

						av_frame_free (&ff_output[i].frame);	

						i++;
						marginLeft += width;	

            		}
            		marginLeft = 0;
            		marginTop += height;
            	}
            	marginTop = 0; 
            	i = 0;
            	inc++;
			}
			av_frame_free (&ff_input.frame);
		}
	}

	return 0;
}
Example #12
0
void CPlayer::Reset()
{
	m_DieTick = Server()->Tick();
	m_JoinTick = Server()->Tick();
	if (m_pCharacter)
		delete m_pCharacter;
	m_pCharacter = 0;
	m_KillMe = 0;
	m_SpectatorID = SPEC_FREEVIEW;
	m_LastActionTick = Server()->Tick();
	m_TeamChangeTick = Server()->Tick();
	m_WeakHookSpawn = false;

	int* idMap = Server()->GetIdMap(m_ClientID);
	for (int i = 1;i < VANILLA_MAX_CLIENTS;i++)
	{
		idMap[i] = -1;
	}
	idMap[0] = m_ClientID;

	// DDRace

	m_LastCommandPos = 0;
	m_LastPlaytime = time_get();
	m_Sent1stAfkWarning = 0;
	m_Sent2ndAfkWarning = 0;
	m_ChatScore = 0;
	m_EyeEmote = true;
	m_TimerType = g_Config.m_SvDefaultTimerType;
	m_DefEmote = EMOTE_NORMAL;
	m_Afk = false;
	m_LastWhisperTo = -1;
	m_LastSetSpectatorMode = 0;
	m_TimeoutCode[0] = '\0';

	m_TuneZone = 0;
	m_TuneZoneOld = m_TuneZone;
	m_Halloween = false;
	m_FirstPacket = true;

	m_SendVoteIndex = -1;

	if (g_Config.m_SvEvents)
	{
		time_t rawtime;
		struct tm* timeinfo;
		char d[16], m[16], y[16];
		int dd, mm;
		time ( &rawtime );
		timeinfo = localtime ( &rawtime );
		strftime (d,sizeof(y),"%d",timeinfo);
		strftime (m,sizeof(m),"%m",timeinfo);
		strftime (y,sizeof(y),"%Y",timeinfo);
		dd = atoi(d);
		mm = atoi(m);
		if ((mm == 12 && dd == 31) || (mm == 1 && dd == 1))
		{ // New Year
			m_DefEmote = EMOTE_HAPPY;
		}
		else if ((mm == 10 && dd == 31) || (mm == 11 && dd == 1))
		{ // Halloween
			m_DefEmote = EMOTE_ANGRY;
			m_Halloween = true;
		}
		else
		{
			m_DefEmote = EMOTE_NORMAL;
		}
	}
	m_DefEmoteReset = -1;

	GameServer()->Score()->PlayerData(m_ClientID)->Reset();

	m_ClientVersion = VERSION_VANILLA;
	m_ShowOthers = g_Config.m_SvShowOthersDefault;
	m_ShowAll = g_Config.m_SvShowAllDefault;
	m_SpecTeam = 0;
	m_NinjaJetpack = false;

	m_Paused = PAUSED_NONE;
	m_DND = false;

	m_NextPauseTick = 0;

	// Variable initialized:
	m_Last_Team = 0;
#if defined(CONF_SQL)
	m_LastSQLQuery = 0;
#endif

	int64 Now = Server()->Tick();
	int64 TickSpeed = Server()->TickSpeed();
	// If the player joins within ten seconds of the server becoming
	// non-empty, allow them to vote immediately. This allows players to
	// vote after map changes or when they join an empty server.
	//
	// Otherwise, block voting for 60 seconds after joining.
	if(Now > GameServer()->m_NonEmptySince + 10 * TickSpeed)
		m_FirstVoteTick = Now + g_Config.m_SvJoinVoteDelay * TickSpeed;
	else
		m_FirstVoteTick = Now;
}
Example #13
0
static void
peek_report(const struct peak_packet *packet, const struct peak_track *flow,
    const timeslice_t *timer)
{
	unsigned int i;

	for (i = 0; i < use_count; ++i) {
		if (i) {
			pout(", ");
		}

		switch (use_print[i]) {
		case USE_APP:
			pout("app: %s",
			    peak_li_name(peak_li_merge(flow->li)));
			break;
		case USE_APP_LEN:
			pout("app_len: %hu", packet->app_len);
			break;
		case USE_FLOW:
			pout("flow: %llu", (unsigned long long)flow->id);
			break;
		case USE_IP_LEN:
			pout("ip_len: %hu", packet->net_len);
			break;
		case USE_IP_TYPE:
			pout("ip_type: %hhu", packet->net_type);
			break;
		case USE_SRC:
			if (packet->net_family == AF_INET6 &&
			    packet->flow_sport) {
				pout("src: [%s]%s",
				    netprint(&packet->net_saddr),
				    portprint(packet->flow_sport));
			} else {
				pout("src: %s%s",
				    netprint(&packet->net_saddr),
				    portprint(packet->flow_sport));
			}
			break;
		case USE_DST:
			if (packet->net_family == AF_INET6 &&
			    packet->flow_dport) {
				pout("dst: [%s]%s",
				    netprint(&packet->net_daddr),
				    portprint(packet->flow_dport));
			} else {
				pout("dst: %s%s",
				    netprint(&packet->net_daddr),
				    portprint(packet->flow_dport));
			}
			break;
		case USE_TIME: {
			char tsbuf[40];
			pout("time: %s.%06ld", strftime(tsbuf, sizeof(tsbuf),
			    OUTPUT_TIME, &timer->gmt) ? tsbuf : "????",
			    timer->tv.tv_usec);
			break;
		}
		default:
			break;
		}
	}

	pout("\n");
}
int main(int argc, char* argv[])
{
    DIR *mydir;
    struct dirent *myfile;
    struct stat mystat;
    struct passwd *usr;
    struct group *grp;
    struct tm *tme;
    char buf[512];
    char fileperm[512];
    char tmbuf[100];    

	if(argv[1]==NULL){
  		perror("usage ./a.out file/directory_name\n");
  		exit(0);
  	}
  	
  	if((mydir = opendir(argv[1]))==NULL){
  		perror("no such file or directory\n");
  		exit(0);
  	}
  	
	
	usr=getpwuid(mystat.st_mode);
    grp=getgrgid(mystat.st_mode);
    while((myfile = readdir(mydir)) != NULL){
            sprintf(buf, "%s/%s", argv[1], myfile->d_name);   //appends the filename with the path
    		if((lstat(buf, &mystat))<0){
    			perror("stat error\n");
    		}  
    		
	 	    switch (mystat.st_mode & S_IFMT) {
        	    case S_IFDIR:  printf("d ");            break;
        		case S_IFREG:  printf("r ");            break;
        		default:       printf("- ");            break;
    		}
    		
    		tme=localtime(&mystat.st_mtime);
    		strftime(tmbuf,sizeof(tmbuf),"%A %B %H:%M:%S",tme);
    		 
    		sprintf(fileperm,"%c%c%c%c%c%c%c%c%c",
    		(mystat.st_mode)& S_IRUSR ? 'r':'-',
    		(mystat.st_mode)& S_IWUSR ? 'w':'-',
    		(mystat.st_mode)& S_IXUSR ? 'x':'-',
    		(mystat.st_mode)& S_IRGRP ? 'r':'-',
    		(mystat.st_mode)& S_IRGRP ? 'w':'-',
    		(mystat.st_mode)& S_IXGRP ? 'x':'-',
    		(mystat.st_mode)& S_IROTH ? 'r':'-',
    		(mystat.st_mode)& S_IWOTH ? 'w':'-',
    		(mystat.st_mode)& S_IXOTH ? 'x':'-'
    		);
    		
    		printf("%s ",fileperm);
    		printf("%d ",mystat.st_nlink);
    		printf("%s ",usr->pw_name);
    		printf("%s ",grp->gr_name);
    		printf("%s",tmbuf);
    		printf("%d ",mystat.st_size);
    		printf("%s\n", myfile->d_name);
        
    	}
    	closedir(mydir);
	return 0;



}
Example #15
0
/*
 * Handle gopher menus
 */
void gopher_menu(state *st)
{
	FILE *fp;
	sdirent dir[MAX_SDIRENT];
	struct tm *ltime;
	struct stat file;
	char buf[BUFSIZE];
	char pathname[BUFSIZE];
	char displayname[BUFSIZE];
	char encodedname[BUFSIZE];
	char timestr[20];
	char sizestr[20];
	char *parent;
	char *c;
	char type;
	int width;
	int num;
	int i;
	int n;

	/* Check for a gophermap */
	snprintf(pathname, sizeof(pathname), "%s/%s",
		st->req_realpath, st->map_file);

	if (stat(pathname, &file) == OK &&
	    (file.st_mode & S_IFMT) == S_IFREG) {

		/* Parse gophermap */
		if (gophermap(st, pathname, 0) == QUIT) {
			footer(st);
			return;
		}
	}

	else {
		/* Check for a gophertag */
		snprintf(pathname, sizeof(pathname), "%s/%s",
			st->req_realpath, st->tag_file);

		if (stat(pathname, &file) == OK &&
		    (file.st_mode & S_IFMT) == S_IFREG) {

			/* Read & output gophertag */
			if ((fp = fopen(pathname , "r"))) {

				fgets(buf, sizeof(buf), fp);
				chomp(buf);

				info(st, buf, TYPE_TITLE);
				info(st, EMPTY, TYPE_INFO);
				fclose(fp);
			}
		}

		/* No gophermap or tag found - print default header */
		else if (st->opt_header) {

			/* Use the selector as menu title */
			sstrlcpy(displayname, st->req_selector);

			/* Shorten too long titles */
			while (strlen(displayname) > (st->out_width - sizeof(HEADER_FORMAT))) {
				if ((c = strchr(displayname, '/')) == NULL) break;

				if (!*++c) break;
				sstrlcpy(displayname, c);
			}

			/* Output menu title */
			snprintf(buf, sizeof(buf), HEADER_FORMAT, displayname);
			info(st, buf, TYPE_TITLE);
			info(st, EMPTY, TYPE_INFO);
		}
	}

	/* Scan the directory */
	num = sortdir(st->req_realpath, dir, MAX_SDIRENT);
	if (num < 0) die(st, ERR_NOTFOUND, "WTF?");

	/* Create link to parent directory */
	if (st->opt_parent) {
		sstrlcpy(buf, st->req_selector);
		parent = dirname(buf);

		/* Root has no parent */
		if (strcmp(st->req_selector, ROOT) != MATCH) {

			/* Prevent double-slash */
			if (strcmp(parent, ROOT) == MATCH) parent++;

			/* Print link */
			printf("1%-*s\t%s/\t%s\t%i" CRLF,
				st->opt_date ? (st->out_width - 1) : (int) strlen(PARENT),
				PARENT, parent, st->server_host, st->server_port);
		}
	}

	/* Width of filenames for fancy listing */
	width = st->out_width - DATE_WIDTH - 15;

	/* Loop through the directory entries */
	for (i = 0; i < num; i++) {

		/* Get full path+name */
		snprintf(pathname, sizeof(pathname), "%s/%s",
			st->req_realpath, dir[i].name);

		/* Skip dotfiles and non world-readables */
		if (dir[i].name[0] == '.') continue;
		if ((dir[i].mode & S_IROTH) == 0) continue;

		/* Skip gophermaps and tags (but not dirs) */
		if ((dir[i].mode & S_IFMT) != S_IFDIR) {
			if (strcmp(dir[i].name, st->map_file) == MATCH) continue;
			if (strcmp(dir[i].name, st->tag_file) == MATCH) continue;
		}

		/* Skip files marked for hiding */
		for (n = 0; n < st->hidden_count; n++)
			if (strcmp(dir[i].name, st->hidden[n]) == MATCH) break;
		if (n < st->hidden_count) continue;	/* Cruel hack... */

		/* Generate display name with correct output charset */
		if (st->opt_iconv)
			sstrniconv(st->out_charset, displayname, dir[i].name);
		else
			sstrlcpy(displayname, dir[i].name);

		/* #OCT-encode filename */
		strnencode(encodedname, dir[i].name, sizeof(encodedname));

		/* Handle inline .gophermap */
		if (strstr(displayname, st->map_file) > displayname) {
			gophermap(st, pathname, 0);
			continue;
		}

		/* Handle directories */
		if ((dir[i].mode & S_IFMT) == S_IFDIR) {

			/* Check for a gophertag */
			snprintf(buf, sizeof(buf), "%s/%s",
				pathname, st->tag_file);

			if (stat(buf, &file) == OK &&
			    (file.st_mode & S_IFMT) == S_IFREG) {

				/* Use the gophertag as displayname */
				if ((fp = fopen(buf , "r"))) {

					fgets(buf, sizeof(buf), fp);
					chomp(buf);
					fclose(fp);

					/* Skip empty gophertags */
					if (*buf) {

						/* Convert to output charset */
						if (st->opt_iconv) sstrniconv(st->out_charset, displayname, buf);
						else sstrlcpy(displayname, buf);
					}

				}
			}

			/* Dir listing with dates */
			if (st->opt_date) {
				ltime = localtime(&dir[i].mtime);
				strftime(timestr, sizeof(timestr), DATE_FORMAT, ltime);

				/* Hack to get around UTF-8 byte != char */
				n = width - strcut(displayname, width);
				strrepeat(buf, ' ', n);

				printf("1%s%s   %s        -  \t%s%s/\t%s\t%i" CRLF,
					displayname,
					buf,
					timestr,
					st->req_selector,
					encodedname,
					st->server_host,
					st->server_port);
			}

			/* Regular dir listing */
			else {
				strcut(displayname, st->out_width);
				printf("1%s\t%s%s/\t%s\t%i" CRLF,
					displayname,
					st->req_selector,
					encodedname,
					st->server_host,
					st->server_port);
			}

			continue;
		}

		/* Skip special files (sockets, fifos etc) */
		if ((dir[i].mode & S_IFMT) != S_IFREG) continue;

		/* Get file type */
		type = gopher_filetype(st, pathname, st->opt_magic);

		/* File listing with dates & sizes */
		if (st->opt_date) {
			ltime = localtime(&dir[i].mtime);
			strftime(timestr, sizeof(timestr), DATE_FORMAT, ltime);
			strfsize(sizestr, dir[i].size, sizeof(sizestr));

			/* Hack to get around UTF-8 byte != char */
			n = width - strcut(displayname, width);
			strrepeat(buf, ' ', n);

			printf("%c%s%s   %s %s\t%s%s\t%s\t%i" CRLF, type,
				displayname,
				buf,
				timestr,
				sizestr,
				st->req_selector,
				encodedname,
				st->server_host,
				st->server_port);
		}

		/* Regular file listing */
		else {
			strcut(displayname, st->out_width);
			printf("%c%s\t%s%s\t%s\t%i" CRLF, type,
				displayname,
				st->req_selector,
				encodedname,
				st->server_host,
				st->server_port);
		}
	}

	/* Print footer */
	footer(st);
}
Example #16
0
int popc_logger_t(LOGLEVEL level, const char* file, int line, const char* function, const char* tag, const char* format,
                  ...) {
    // Check if message level in higher than our threshold
    if (level < MIN_LOG_LEVEL)
        return 0;

    // Use file name without path to avoid having the full user path in logs
    const char* basename = strrchr(file, '/');
    if (basename == nullptr)
        basename = file;
    else
        basename += 1;

    auto log_file = get_log_file();

    // Time
    time_t rawtime;
    time(&rawtime);
    const tm* timeinfo = localtime(&rawtime);
    char dd[20];
    strftime(dd, sizeof(dd), "%Y-%m-%d %H:%M:%S", timeinfo);

    char msg[512];
    va_list ap;
    va_start(ap, format);
    vsnprintf(msg, sizeof(msg), format, ap);
    va_end(ap);

    auto msg_length = strlen(msg);
    if (msg[msg_length - 1] == '\n') {
        msg[msg_length - 1] = ' ';
    }

    // Print the message to stderr or stdout
    if (level >= MIN_STDERR_LEVEL)
        if (tag) {
            fprintf(stderr, "%s %5d %s [%5s] %s (%s:%d %s)\n", dd, getpid(), get_prefix(level), tag, msg, basename,
                    line, function);
        } else {
            fprintf(stderr, "%s %5d %s %s (%s:%d %s)\n", dd, getpid(), get_prefix(level), msg, basename, line,
                    function);
        }
    else if (level >= MIN_STDOUT_LEVEL)
        fprintf(stdout, "%s\n", msg);

    // Print the message to file
    FILE* f = fopen(log_file.c_str(), "a");
    if (f == NULL) {
        fprintf(stderr, "ERROR: Impossible to open log file %s\n", log_file.c_str());
        return 1;
    }

    if (tag) {
        fprintf(f, "%s %5d %s [%5s] %s (%s:%d %s)\n", dd, getpid(), get_prefix(level), tag, msg, basename, line,
                function);
    } else {
        fprintf(f, "%s %5d %s %s (%s:%d %s)\n", dd, getpid(), get_prefix(level), msg, basename, line, function);
    }

    fclose(f);
    return 0;
}
Example #17
0
bool Aeromatic::fdm()
{
    Aircraft *aircraft = _aircraft[_atype];
    std::vector<System*> systems = _aircraft[_atype]->get_systems();

    _engines = _MIN(_no_engines, 4);
    aircraft->_engines = _engines;


//***** METRICS ***************************************
    _payload = _max_weight;
    _stall_weight = _max_weight;

    // first, estimate wing loading in psf
    float wing_loading = aircraft->get_wing_loading();

    // if no wing area given, use wing loading to estimate
    bool wingarea_input;
    if (_wing.area == 0)
    {
        wingarea_input = false;
        _wing.area = _max_weight / wing_loading;
    }
    else
    {
        wingarea_input = true;
        wing_loading = _max_weight / _wing.area;
    }

    // calculate wing chord
    if (_wing.aspect == 0) {
        _wing.aspect = aircraft->get_aspect_ratio();
    } else {
        _user_wing_data++;
    }
    if (_wing.chord == 0)
    {
        if (_wing.aspect > 0) {
            _wing.chord = _wing.span / _wing.aspect;
        } else {
            _wing.chord = _wing.area / _wing.span;
        }
    }
    else {
        _user_wing_data++;
    }

    // calculate aspect ratio
    if (_wing.aspect == 0) {
        _wing.aspect = (_wing.span*_wing.span) / _wing.area;
    } else {
        _user_wing_data++;
    }

    if (_wing.taper == 0) {
        _wing.taper = 1.0f;
    }

    float TR = _wing.taper;
    _wing.chord_mean = 0.75f*_wing.chord*(1.0f+TR+TR*TR)/(1.0f+TR);
    _wing.de_da = 4.0f/(_wing.aspect+2.0f);

    // leading edge sweep
    // devide the span by two and account for fuselage width
    float span = 0.45f*_wing.span;
    float root_tip = _wing.chord*(1.0f - _wing.taper);

    if (_wing.sweep_le == 0)
    {
        _wing.sweep_le = atanf(root_tip/span);
        if (_wing.shape != DELTA) {
            _wing.sweep_le *= 0.5f;
        }
        _wing.sweep_le *= RAD_TO_DEG;
        _wing.sweep_le += _wing.sweep;
    }

    if (_wing.thickness == 0)
    {
        // Hofman equation for t/c
//      float Ws = _stall_weight;
        float Vs = _stall_speed * KNOTS_TO_FPS;
        float sweep = _wing.sweep * DEG_TO_RAD;
        float TC = 0.051f * _wing.area * powf(cosf(sweep), 5.0f)/Vs;
        _wing.thickness = TC * _wing.chord;
    }

    // for now let's use a standard 2 degrees wing incidence
    if (_wing.incidence == 0) {
        _wing.incidence = 2.0;
    }

    // estimate horizontal tail area
    if (_htail.area == 0) {
        _htail.area = _wing.area * aircraft->get_htail_area();
    }

    // estimate distance from CG to horizontal tail aero center
    if (_htail.arm == 0) {
        _htail.arm = _length * aircraft->get_htail_arm();
    }

    if (_htail.aspect == 0) {
        _htail.aspect = 5.0f;	// ht_w * _wing.aspect;
    }
    if (_htail.taper == 0) {
        _htail.taper = 0.5f;
    }

    float ht_w = 0.33f; // sqrtf(_htail.area / _wing.area);
    if (_htail.span == 0) {
        _htail.span = ht_w * _wing.span;
    }

    TR = _htail.taper;
    _htail.chord_mean = 0.75f*_htail.chord*(1.0f+TR+TR*TR)/(1.0f+TR);
    _htail.de_da = 4.0f/(_htail.aspect+2.0f);

    // estimate vertical tail area
    if (_vtail.area == 0) {
        _vtail.area = _wing.area * aircraft->get_vtail_area();
    }

    // estimate distance from CG to vertical tail aero center
    if (_vtail.arm == 0) {
        _vtail.arm = _length * aircraft->get_vtail_arm();
    }

    float vt_w = 0.15f; // sqrtf(_vtail.area / _wing.area*0.5f);
    if (_vtail.span == 0) {
        _vtail.span = vt_w * _wing.span;
    }
    if (_vtail.aspect == 0) {
        _vtail.aspect = 1.7f;	// vt_w * _wing.aspect;
    }
    if (_vtail.taper == 0) {
        _vtail.taper = 0.7f;
    }

    TR = _vtail.taper;
    _vtail.chord_mean = 0.75f*_vtail.chord*(1.0f+TR+TR*TR)/(1.0f+TR);
    _vtail.de_da = 4.0f/(_vtail.aspect+2.0f);

//***** EMPTY WEIGHT *********************************

    // estimate empty weight, based on max weight
    if (_empty_weight == 0) {
        _empty_weight = _max_weight * aircraft->get_empty_weight();
    }

//***** MOMENTS OF INERTIA ******************************

    // use Roskam's formulae to estimate moments of inertia
    if (_inertia[X] == 0.0f && _inertia[Y] == 0.0f && _inertia[Z] == 0.0f)
    {
        float slugs = (_empty_weight / 32.2f);	// sluggishness
        const float *R = aircraft->get_roskam();

        // These are for an empty airplane
        _inertia[X] = slugs * powf((R[X] * _wing.span / 2), 2);
        _inertia[Y] = slugs * powf((R[Y] * _length / 2), 2);
        _inertia[Z] = slugs * powf((R[Z] * ((_wing.span + _length)/2)/2), 2);
    }

//***** CG LOCATION ***********************************

    _cg_loc[X] = (_length - _htail.arm) * FEET_TO_INCH;
    _cg_loc[Y] = 0;
    _cg_loc[Z] = -(_length / 40.0f) * FEET_TO_INCH;

//***** AERO REFERENCE POINT **************************

    _aero_rp[X] = _cg_loc[X];
    _aero_rp[Y] = 0;
    _aero_rp[Z] = 0;

//***** PILOT EYEPOINT *********************************

    // place pilot's eyepoint based on airplane type
    const float *_eyept_loc = aircraft->get_eyept_loc();
    float eyept_loc[3];
    eyept_loc[X] = (_length * _eyept_loc[X]) * FEET_TO_INCH;
    eyept_loc[Y] = _eyept_loc[Y];
    eyept_loc[Z] = _eyept_loc[Z];

//***** PAYLOAD ***************************************

    // A point mass will be placed at the CG weighing
    // 1/2 of the usable aircraft load.
    float payload_loc[3];
    payload_loc[X] = _cg_loc[X];
    payload_loc[Y] = _cg_loc[Y];
    payload_loc[Z] = _cg_loc[Z];
    _payload -= _empty_weight;

//***** SYSTEMS ***************************************
    for (unsigned i=0; i<systems.size(); ++i)
    {
        if (systems[i]->enabled()) {
            systems[i]->set(_cg_loc);
        }
    }

//***** COEFFICIENTS **********************************
    aircraft->set_lift();
    aircraft->set_drag();
    aircraft->set_side();
    aircraft->set_roll();
    aircraft->set_pitch();
    aircraft->set_yaw();

//************************************************
//*                                              *
//*  Print out xml document                      *
//*                                              *
//************************************************

    char str[64];
    time_t t;

    time(&t);
#ifdef _MSC_VER
    struct tm ti;
    localtime_s(&ti, &t);
    strftime(str, sizeof(str), "%d %b %Y", &ti);
#else
    struct tm *ti= localtime(&t);
    strftime(str, sizeof(str), "%d %b %Y", ti);
#endif

    _dir = _subdir ? create_dir(_path, _name) : _path;
    if (_dir.empty()) {
        std::cout << "Unable to create directory: " << _path << "/" << _name << std::endl;
        return false;
    }

    std::string systems_dir;
    if (_system_files)
    {
        systems_dir = create_dir(_dir, "Systems");
        if (systems_dir.empty())
        {
            std::cout << "Unable to create directory: " << _dir<< "/Systems" << std::endl;
            _system_files = false;
        }
    }

    std::string fname = _dir + "/" + std::string(_name) + ".xml";

    std::string version = AEROMATIC_VERSION_STR;

    if (!_overwrite && overwrite(fname)) {
        std::cout << "File already exists: " << fname << std::endl;
        return false;
    }

    std::ofstream file;
    file.open(fname.c_str());
    if (file.fail() || file.bad())
    {
        file.close();
        return false;
    }

    file.precision(2);
    file.flags(std::ios::right);
    file << std::fixed << std::showpoint;

    file << "<?xml version=\"1.0\"?>" << std::endl;
    file << "<?xml-stylesheet type=\"text/xsl\" href=\"http://jsbsim.sourceforge.net/JSBSim.xsl\"?>" << std::endl;
    file << std::endl;
    file << "<fdm_config name=\"" << _name << "\" version=\"2.0\" release=\"ALPHA\"" << std::endl;
    file << "   xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" << std::endl;
    file << "   xsi:noNamespaceSchemaLocation=\"http://jsbsim.sourceforge.net/JSBSim.xsd\">" << std::endl;
    file << std::endl;
    file << " <fileheader>" << std::endl;
    file << "  <author> Aeromatic v " << version << " </author>" << std::endl;
    file << "  <filecreationdate> " << str << " </filecreationdate>" << std::endl;
    file << "  <version>$Revision: 1.50 $</version>" << std::endl;
    file << "  <description> Models a " << _name << ". </description>" << std::endl;
    file << " </fileheader>" << std::endl;
    file << std::endl;
    file << "<!--\n  File:     " << _name << ".xml" << std::endl;
    file << "  Inputs:" << std::endl;
    file << "    name:          " << _name << std::endl;
    file << "    type:          ";
    switch(_atype)
    {
    case LIGHT:
        if (_no_engines == 0) {
            file << "glider" << std::endl;
        } else {
            file << "light commuter with " << _no_engines << " engines" << std::endl;
        }
        break;
    case PERFORMANCE:
        file << "WWII fighter, subsonic sport, aerobatic" << std::endl;
        break;
    case FIGHTER:
        file << _no_engines << " engine transonic/supersonic fighter" << std::endl;
        break;
    case JET_TRANSPORT:
        file << _no_engines << " engine transonic transport" << std::endl;
        break;
    case PROP_TRANSPORT:
        file << "multi-engine prop transport" << std::endl;
        break;
    }
    file << "    stall speed:   " << _stall_speed << "kts" << std::endl;
    file << "    max weight:    " << _max_weight << " lb" << std::endl;
    file << "    length:        " << _length << " ft" << std::endl;
    file << "    wing: " << std::endl;
    file << "     span:         " << _wing.span << " ft" << std::endl;
    file << "     area:         ";
    if (wingarea_input) {
        file << _wing.area << " sq-ft" << std::endl;
    } else {
        file << "unspecified" << std::endl;
    }
    file << "     chord:        " << _wing.chord << " ft" << std::endl;
    file << "     aspect ratio: " << _wing.aspect << ":1" << std::endl;
    file << "     taper ratio:  " << _wing.taper << ":1" << std::endl;
    file << "     incidence:    " << _wing.incidence << " degrees" << std::endl;
    file << "     dihedral:     " << _wing.dihedral << " degrees" << std::endl;
    file << "     sweep:        " << _wing.sweep << " degrees" << std::endl;
    file << std::endl;

    for (unsigned i=0; i<systems.size(); ++i)
    {
        if (systems[i]->enabled()) {
            std::string comment = systems[i]->comment();
            if (!comment.empty()) {
                file << comment << std::endl;
            }
        }
    }

    file << "  Outputs:" << std::endl;
    file << "    wing loading:  " << wing_loading << " lb/sq-ft" << std::endl;
    file << "    payload:       " << _payload << " lbs" << std::endl;
    file << "    CL-alpha:      " << _CLalpha[0] << " per radian" << std::endl;
    file << "    CL-0:          " << _CL0 << std::endl;
    file << "    CL-max:        " << _CLmax[0] << std::endl;
    file << "    CD-0:          " << _CD0 << std::endl;
    file << "    K:             " << _Kdi << std::endl;
    file << "    Mcrit:         " << _Mcrit << std::endl;
    file << "-->" << std::endl;
    file << std::endl;

//***** METRICS **********************************

    file << " <metrics>" << std::endl;
    file << "   <wingarea  unit=\"FT2\"> " << std::setw(8) << _wing.area << " </wingarea>" << std::endl;
    file << "   <wingspan  unit=\"FT\" > " << std::setw(8) << _wing.span << " </wingspan>" << std::endl;
    file << "   <wing_incidence>       " << std::setw(8) << _wing.incidence << " </wing_incidence>" << std::endl;
    file << "   <chord     unit=\"FT\" > " << std::setw(8) << _wing.chord << " </chord>" << std::endl;
    file << "   <htailarea unit=\"FT2\"> " << std::setw(8) << _htail.area << " </htailarea>" << std::endl;
    file << "   <htailarm  unit=\"FT\" > " << std::setw(8) << _htail.arm << " </htailarm>" << std::endl;
    file << "   <vtailarea  unit=\"FT2\">" << std::setw(8) << _vtail.area << " </vtailarea>" << std::endl;
    file << "   <vtailarm  unit=\"FT\" > " << std::setw(8) << _vtail.arm << " </vtailarm>" << std::endl;
    file << "   <location name=\"AERORP\" unit=\"IN\">" << std::endl;
    file << "     <x> " << std::setw(8) << _aero_rp[X] << " </x>" << std::endl;
    file << "     <y> " << std::setw(8) << _aero_rp[Y] << " </y>" << std::endl;
    file << "     <z> " << std::setw(8) << _aero_rp[Z] << " </z>" << std::endl;
    file << "   </location>" << std::endl;
    file << "   <location name=\"EYEPOINT\" unit=\"IN\">" << std::endl;
    file << "     <x> " << std::setw(8) << eyept_loc[X] << " </x>" << std::endl;
    file << "     <y> " << std::setw(8) << eyept_loc[Y] << " </y>" << std::endl;
    file << "     <z> " << std::setw(8) << eyept_loc[Z] << " </z>" << std::endl;
    file << "   </location>" << std::endl;
    file << "   <location name=\"VRP\" unit=\"IN\">" << std::endl;
    file << "     <x>     0.0 </x>" << std::endl;
    file << "     <y>     0.0 </y>" << std::endl;
    file << "     <z>     0.0 </z>" << std::endl;
    file << "   </location>" << std::endl;
    file << " </metrics>"<< std::endl;
    file << std::endl;
    file << " <mass_balance>" << std::endl;
    file << "   <ixx unit=\"SLUG*FT2\">  " << std::setw(8) << _inertia[X] << " </ixx>" << std::endl;
    file << "   <iyy unit=\"SLUG*FT2\">  " << std::setw(8) << _inertia[Y] << " </iyy>" << std::endl;
    file << "   <izz unit=\"SLUG*FT2\">  " << std::setw(8) << _inertia[Z] << " </izz>" << std::endl;
    file << "   <emptywt unit=\"LBS\" >  " << std::setw(8) << _empty_weight << " </emptywt>" << std::endl;
    file << "   <location name=\"CG\" unit=\"IN\">" << std::endl;
    file << "     <x> " << std::setw(8) << _cg_loc[X] << " </x>" << std::endl;
    file << "     <y> " << std::setw(8) << _cg_loc[Y] << " </y>" << std::endl;
    file << "     <z> " << std::setw(8) << _cg_loc[Z] << " </z>" << std::endl;
    file << "   </location>" << std::endl;
    file << "   <pointmass name=\"Payload\">" << std::endl;
    file << "    <description> " << _payload << " LBS should bring model up to entered max weight </description>" << std::endl;
    file << "    <weight unit=\"LBS\"> " << (_payload* 0.5f) << " </weight>" << std::endl;
    file << "    <location name=\"POINTMASS\" unit=\"IN\">" << std::endl;
    file << "     <x> " << std::setw(8) << payload_loc[X] << " </x>" << std::endl;
    file << "     <y> " << std::setw(8) << payload_loc[Y] << " </y>" << std::endl;
    file << "     <z> " << std::setw(8) << payload_loc[Z] << " </z>" << std::endl;
    file << "   </location>" << std::endl;
    file << "  </pointmass>" << std::endl;

    for (unsigned i=0; i<systems.size(); ++i)
    {
        if (systems[i]->enabled())
        {
            std::string mass_balance = systems[i]->mass_balance();
            if (!mass_balance.empty()) {
                file << mass_balance << std::endl;
            }
        }
    }

    file << " </mass_balance>" << std::endl;
    file << std::endl;

//***** FDM_CONFIG ********************************************

    for (unsigned i=0; i<systems.size(); ++i)
    {
        if (systems[i]->enabled())
        {
            std::string fdm = systems[i]->fdm();
            if (!fdm.empty()) {
                file << fdm << std::endl;
            }
        }
    }

//***** SYSTEMS ***********************************************

    if (_system_files == true)
    {
        for (unsigned i=0; i<systems.size(); ++i)
        {
            if (systems[i]->enabled())
            {
                std::string system = systems[i]->system();
                if (!system.empty())
                {
                    std::string sname = systems[i]->get_description();
                    std::string sfname = sname + ".xml";

                    if (!_overwrite && overwrite(sfname))
                    {
                        std::cout << "File already exists: " << fname << std::endl;
                        std::cout << "Skipping." << std::endl;
                    }
                    else
                    {
                        file << " <system file=\"" << sfname << "\"/>" << std::endl;

                        std::string sfpath = systems_dir + "/" + sfname;
                        std::ofstream sfile;
                        sfile.open(sfpath.c_str());
                        if (sfile.fail() || sfile.bad())
                        {
                            std::cout << "Error opening file: " << fname << std::endl;
                            std::cout << "Skipping." << std::endl;
                        }
                        else
                        {
                            sfile << "<?xml version=\"1.0\"?>" << std::endl;
                            sfile << "<system name=\"" << sname << "\">" << std::endl;
                            sfile << system << std::endl;
                            sfile << "</system>" << std::endl;
                        }
                        sfile.close();
                    }
                }
            }
        }
        file << std::endl;
    }

    file << " <flight_control name=\"FCS: " << _name << "\">" << std::endl;
    file << std::endl;

    if (_system_files == false)
    {
        for (unsigned i=0; i<systems.size(); ++i)
        {
            if (systems[i]->enabled())
            {
                std::string system = systems[i]->system();
                if (!system.empty()) {
                    file << system << std::endl;
                }
            }
        }
    }

    file << " </flight_control>"<< std::endl;
    file << std::endl;

//***** AERODYNAMICS ******************************************

    file << " <aerodynamics>" << std::endl;
    file << std::endl;

    // ***** LIFT ******************************************

    file << "  <axis name=\"LIFT\">" << std::endl;
    file << std::endl;

    for (unsigned i=0; i<systems.size(); ++i)
    {
        if (systems[i]->enabled())
        {
            std::string lift = systems[i]->lift();
            if (!lift.empty()) {
                file << lift << std::endl;
            }
        }
    }

    file << "  </axis>" << std::endl;
    file << std::endl;

    // ***** DRAG ******************************************

    file << "  <axis name=\"DRAG\">" << std::endl;
    file << std::endl;

    for (unsigned i=0; i<systems.size(); ++i)
    {
        if (systems[i]->enabled())
        {
            std::string drag = systems[i]->drag();
            if (!drag.empty()) {
               file << drag << std::endl;
            }
        }
    }

    file << "  </axis>" << std::endl;
    file << std::endl;

    // ***** SIDE ******************************************

    file << "  <axis name=\"SIDE\">" << std::endl;
    file << std::endl;

    for (unsigned i=0; i<systems.size(); ++i)
    {
        if (systems[i]->enabled())
        {
            std::string side = systems[i]->side();
            if (!side.empty()) {
                file << side << std::endl;
            }
        }
    }

    file << "  </axis>" << std::endl;
    file << std::endl;

    // ***** PITCH *****************************************

    file << "  <axis name=\"PITCH\">" << std::endl;
    file << std::endl;

    for (unsigned i=0; i<systems.size(); ++i)
    {
        if (systems[i]->enabled())
        {
            std::string pitch = systems[i]->pitch();
            if (!pitch.empty()) {
                file << pitch << std::endl;
            }
        }
    }

    file << "  </axis>" << std::endl;
    file << std::endl;

    // ***** ROLL ******************************************

    file << "  <axis name=\"ROLL\">" << std::endl;
    file << std::endl;

    for (unsigned i=0; i<systems.size(); ++i)
    {
        if (systems[i]->enabled())
        {
            std::string roll = systems[i]->roll();
            if (!roll.empty()) {
                file << roll << std::endl;
            }
        }
    }

    file << "  </axis>" << std::endl;
    file << std::endl;

    // ***** YAW *******************************************

    file << "  <axis name=\"YAW\">" << std::endl;
    file << std::endl;

    for (unsigned i=0; i<systems.size(); ++i)
    {
        if (systems[i]->enabled())
        {
            std::string yaw = systems[i]->yaw();
            if (!yaw.empty()) {
                file << yaw << std::endl;
            }
        }
    }

    file << "  </axis>" << std::endl;
    file << std::endl;
    
    file << " </aerodynamics>" << std::endl;
    file << std::endl;

    file << " <external_reactions>" << std::endl;

    for (unsigned i=0; i<systems.size(); ++i)
    {
        if (systems[i]->enabled())
        {
            std::string force = systems[i]->external_force();
            if (!force.empty()) {
                file << force << std::endl;
            }
        }
    }

    file << " </external_reactions>" << std::endl;

    file << std::endl;
    file << "</fdm_config>" << std::endl;

    file.close();

    return true;
}
    void pre(std::ostream& out, Actions& actions)
    {
        // The quickbook file has been parsed. Now, it's time to
        // generate the output. Here's what we'll do *before* anything else.

        if (actions.doc_id.empty())
            actions.doc_id = detail::make_identifier(
                actions.doc_title.begin(),actions.doc_title.end());

        if (actions.doc_dirname.empty())
            actions.doc_dirname = actions.doc_id;

        if (actions.doc_last_revision.empty())
        {
            // default value for last-revision is now

            char strdate[ 30 ];
            time_t t = time(0);
            strftime(
                strdate, sizeof(strdate),
                "$" /* prevent CVS substitution */ "Date: %Y/%m/%d %H:%M:%S $",
                gmtime(&t)
            );

            actions.doc_last_revision = strdate;
        }

        out << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
            << "<!DOCTYPE library PUBLIC \"-//Boost//DTD BoostBook XML V1.0//EN\"\n"
            << "     \"http://www.boost.org/tools/boostbook/dtd/boostbook.dtd\">\n"
            << '<' << actions.doc_type << "\n"
            << "    id=\"" << actions.doc_id << "\"\n"
            << "    name=\"" << actions.doc_title << "\"\n"
            << "    dirname=\"" << actions.doc_dirname << "\"\n"
            << "    last-revision=\"" << actions.doc_last_revision << "\" \n"
            << "    xmlns:xi=\"http://www.w3.org/2001/XInclude\">\n"
            << "  <" << actions.doc_type << "info>\n";

        for_each(
            actions.doc_authors.begin()
          , actions.doc_authors.end()
          , xml_author(out));

        if (!actions.doc_copyright_holder.empty())
        {
            out << "\n" << "    <copyright>\n";

            for_each(
                actions.doc_copyright_years.begin()
              , actions.doc_copyright_years.end()
              , xml_year(out));

            out << "      <holder>" << actions.doc_copyright_holder << "</holder>\n"
                << "    </copyright>\n"
                << "\n"
            ;
        }

        if (!actions.doc_license.empty())
        {
            out << "    <legalnotice>\n"
                << "      <para>\n"
                << "        " << actions.doc_license << "\n"
                << "      </para>\n"
                << "    </legalnotice>\n"
                << "\n"
            ;
        }

        if (!actions.doc_purpose.empty())
        {
            out << "    <" << actions.doc_type << "purpose>\n"
                << "      " << actions.doc_purpose
                << "    </" << actions.doc_type << "purpose>\n"
                << "\n"
            ;
        }

        if (!actions.doc_purpose.empty())
        {
            out << "    <" << actions.doc_type << "category name=\"category:"
                << actions.doc_category
                << "\"></" << actions.doc_type << "category>\n"
                << "\n"
            ;
        }

        out << "  </" << actions.doc_type << "info>\n"
            << "\n"
        ;

        if (!actions.doc_title.empty())
        {
            out << "  <title>" << actions.doc_title;
            if (!actions.doc_version.empty())
                out << ' ' << actions.doc_version;
            out << "</title>\n\n\n";
        }
    }
Example #19
0
void Logger::logPrint( bool hex, const char * const file, const int line, const int level, const char *fstring, ... )
{
    if ( level <= mEffectiveLevel )
    {
        char            classString[4];
        char            timeString[64];
        char            logString[8192];
        va_list         argPtr;
        struct timeval  timeVal;
        
        if ( level < PANIC || level > DEBUG9 )
            Panic( "Invalid logger level %d", level );

        strncpy( classString, smCodes[level].c_str(), sizeof(classString) );

        gettimeofday( &timeVal, NULL );

    #if 0
        if ( logRuntime )
        {
            static struct timeval logStart;

            subtractTime( &timeVal, &logStart );

            snprintf( timeString, sizeof(timeString), "%ld.%03ld", timeVal.tv_sec, timeVal.tv_usec/1000 );
        }
        else
        {
    #endif
            char *timePtr = timeString;
            timePtr += strftime( timePtr, sizeof(timeString), "%x %H:%M:%S", localtime(&timeVal.tv_sec) );
            snprintf( timePtr, sizeof(timeString)-(timePtr-timeString), ".%06ld", timeVal.tv_usec );
    #if 0
        }
    #endif

        pid_t tid;
#ifdef HAVE_SYSCALL
        if ( (tid = syscall(SYS_gettid)) < 0 ) // Thread/Process id
#endif // HAVE_SYSCALL
        tid = getpid(); // Process id

        char *logPtr = logString;
        logPtr += snprintf( logPtr, sizeof(logString), "%s %s[%d].%s-%s/%d [", 
                    timeString,
                    mId.c_str(),
                    tid,
                    classString,
                    file,
                    line
                );
        char *syslogStart = logPtr;

        va_start( argPtr, fstring );
        if ( hex )
        {
            unsigned char *data = va_arg( argPtr, unsigned char * );
            int len = va_arg( argPtr, int );
            int i;
            logPtr += snprintf( logPtr, sizeof(logString)-(logPtr-logString), "%d:", len );
            for ( i = 0; i < len; i++ )
            {
                logPtr += snprintf( logPtr, sizeof(logString)-(logPtr-logString), " %02x", data[i] );
            }
        }
        else
        {
Example #20
0
int main(int argc, char *argv[])
{	
	string server("129.194.32.96");
	CalendarController::InputLang lang(CalendarController::INPUT_LANG_ENG);
	
	if (argc >= 2)
	{	
		string arg = argv[1];
		
		if (arg == "ENG")
		{
			lang = CalendarController::INPUT_LANG_ENG;			
		}
		else if (arg == "JAP")
		{
			lang = CalendarController::INPUT_LANG_JAP;		
		}
		else
		{
			lang = CalendarController::INPUT_LANG_ENG;
		}
	}
	
	if (argc == 3)
	{	
		server = argv[2];
	}

	const struct tm* tm;
	size_t len;
	time_t now;
	char* s;
	
	now = time(NULL);
	tm = localtime(&now);
	
	s = new char[40];
	len = strftime(s, 40, "%Y-%m-%d.%H-%M-%S", tm);
	string str(s);
	str = "../logs/test_calendar_gui." + str + ".output";	
	delete s;
	
	ACE_OSTREAM_TYPE* output = 
		new std::ofstream(str.c_str());
	ACE_LOG_MSG->msg_ostream(output, 0);
	ACE_LOG_MSG->set_flags(ACE_Log_Msg::OSTREAM);
	ACE_LOG_MSG->set_flags(ACE_Log_Msg::VERBOSE_LITE);
	
	ACE_LOG_MSG->priority_mask(LM_TRACE|LM_DEBUG, ACE_Log_Msg::PROCESS);
	
	g_thread_init(NULL);
	gdk_threads_init();
	gdk_threads_enter();
	gtk_init(&argc, &argv);
	g_set_application_name(APP_NAME);
	
	CalendarController calendarctl;
	calendarctl.SetRemoteServersIP(server);
	calendarctl.SetInputLang(lang);
	calendarctl.RunApp();

	ACE_LOG_MSG->clr_flags(ACE_Log_Msg::OSTREAM);
	delete output;
	
	gdk_threads_leave();
	
	return 0;    
}
Example #21
0
File: x.c Project: childhood/parcle
int
main(int argc, char *argv[])
{
	fd_set              rfds, wfds;
	struct cn_strct    *tp, *to;
	int                 rnum, wnum, readsocks;
	int                 i;
	struct    tm       *tm_struct;

	/* initialize the masterdate we update only every second */
	_Last_loop = time(NULL);
	tm_struct  = gmtime(&_Last_loop);
	strftime( _Master_date, 32, "%a, %d %b %Y %H:%M:%S %Z", tm_struct);
#if DEBUG_VERBOSE == 2
	_Conn_count=0;
#endif
#if DEBUG_VERBOSE == 1
	printf("STARTED AT: %s\n", _Master_date);
#endif

	signal(SIGQUIT, die);
	signal(SIGTERM, die);
	signal(SIGPIPE, check_sockets);
	signal(SIGINT,  clean_on_quit);

	/* Fill up the initial connection lists; _Free_conns is just a LIFO stack,
	 * there shall never be a performance issues -> single linked only */
	_Free_count=0;
	for (i = 0; i < INITIAL_CONNS; i++) {
		tp = _Free_conns;
		_Free_conns = (struct cn_strct *) calloc(1, sizeof(struct cn_strct));
		_Free_conns->data_buf_head =
			(char *) calloc (RECV_BUFF_LENGTH, sizeof (char));
		_Free_conns->c_next = tp;
		_Free_conns->c_prev = NULL;
		_Free_conns->q_prev = NULL;
		_Free_conns->identifier = _Conn_count++;
		_Free_count++;
	}

	/* create the master listener */
	if ((_Master_sock = create_listener(HTTP_PORT)) == -1) {
		fprintf(stderr, "ERR: Couldn't bind to port %d\n",
				HTTP_PORT);
		exit(1);
	}

	/* set up LIFO queue */
	_Queue_tail = _Queue_head = NULL;
	_Queue_count = 0;

	/* create workers for application */
	for(i = 0; i < WORKER_THREADS; i++) {
		pthread_create(&_Workers[i], NULL, &run_app_thread, (void *) &i);
	}
	sleep(1);
	for(i = 0; i < WORKER_THREADS; i++) {
		pthread_detach( _Workers[i] );
	}

#if DEBUG_VERBOSE == 1
	printf("%s: listening on port %d (http)\n",
			_Server_version, HTTP_PORT);
#endif

	/* main loop */
	while (1) {
		// clean socket lists
		FD_ZERO(&rfds);
		FD_ZERO(&wfds);
		wnum = -1;

		// Add master listener to reading sockets
		FD_SET(_Master_sock, &rfds);
		rnum = _Master_sock;

		// Add the established sockets
		tp = _Busy_conns;

		/* Adding connection to the SocketSets based on state */
		while (tp != NULL) {
			if (REQSTATE_READ_HEAD == tp->req_state) {
				FD_SET(tp->net_socket, &rfds);
				rnum = (tp->net_socket > rnum) ? tp->net_socket : rnum;
			}
			if (REQSTATE_SEND_FILE == tp->req_state) {
				FD_SET(tp->net_socket, &wfds);
				wnum = (tp->net_socket > wnum) ? tp->net_socket : wnum;
			}
			tp = tp->c_next;
		}

		readsocks = select(
			(wnum > rnum) ? wnum+1 : rnum+1,
			(-1 != rnum)  ? &rfds : NULL,
			(-1 != wnum)  ? &wfds : NULL,
			(fd_set *) 0,
			NULL
		);

		// is the main listener in the read set? -> New connection
		if (FD_ISSET(_Master_sock, &rfds)) {
			handle_new_conn(_Master_sock);
			readsocks--;
		}

		// Handle the established sockets
		tp = _Busy_conns;

		while (readsocks > 0 && tp != NULL) {
			to = tp;
			tp = tp->c_next;

			if (REQSTATE_READ_HEAD == to->req_state &&
			  FD_ISSET(to->net_socket, &rfds)) {
				readsocks--;
#if DEBUG_VERBOSE == 1
				printf("WANNA RECV HEAD\n");
#endif
				read_request(to);
			}
			if (REQSTATE_SEND_FILE == to->req_state &&
			  FD_ISSET(to->net_socket, &wfds)) {
				readsocks--;
#if DEBUG_VERBOSE == 1
				printf("WANNA SEND FILE\n");
#endif
				send_file(to);
			}
		}
	}
	return 0;
}
main( void)
{

char * host = "0.0.0.0";
char * service = "2525";
char * proto = "tcp";
//char * proto = "sctp";
struct sockaddr_in sin, remote;
struct tm *tp;
time_t t;
int i, sd, rsd, rlen, readed, pid;
char buf[513], t_str[512];


    if ( (sd = mksock( host, service, proto, &sin)) == -1)
    {
		perror( "Ошибка при создании сокета");
		return 1;
    }

    printf( "Адрес сервера %s = %s\n", host, (char *) (inet_ntoa( sin.sin_addr)));
    printf( "Адрес порта сервера %s = %X\n", service, sin.sin_port);

	
	i = 1;
	i = setsockopt( sd, SOL_SOCKET, SO_REUSEADDR, &i, sizeof( &i));
	if( i != 0) perror("Опция сокета (SOL_SOCKET, SO_REUSEADDR))");

	if( bind( sd, (struct sockaddr *) &sin, sizeof( sin)) < 0)
	{
		perror( "Ошибка при привязке сокета");
		return 1;
	}

	for ( i=0; i<CHILDS; i++)
	{
		pid = fork();
		switch ( pid)
		{
			case -1:
				perror( "Не создается дочерний процесс");
				break;
			case 0:
				pid = i+1;
				i=CHILDS+1;
			break;
			default:
				pid=0;
		}
	}

    if ( listen( sd, 0) == -1)
    {
	perror( "Ошибка при переводе сокета в пассивный режим");
        return 1;
	}

    while(1)
    {
		rlen = sizeof( remote);
		rsd = accept( sd, (struct sockaddr *)&remote, &rlen);
		fprintf( stderr, "Process %d accepted connection\n", pid);
		t = time( NULL);
		tp = localtime( &t);
		strftime( t_str, 512, "%a, %d %b %Y %T %z", tp);
		snprintf( buf, 512, "Server [%d]: %s\n", pid, t_str );
		send(rsd, buf, strlen(buf), 0);
		close( rsd);
    }

    return 0;
}
Example #23
0
void find_hb (char * fname)   
{ 
    int       i, ii, j, jj, k ;
    
    int       debug=0;
    char buf1[20],buf2[20]; /* buffers for atomid routines */
    
    char      calendar_s[128];
    
    /* void find_ss()*/
    /* {*/
    /*     int i,j;*/
    /*     float d;*/
    time_t    calendar;
    struct tm * calendar_tm_p;
    
    char output_string[256]="\0";
    
    /*     /* Check for disulphide bridges */
	
    if (!longoutflg)
    {
 	if (debug) printf("If !longoutflg\n");
 	
 	time ( &calendar );
 	if (debug) printf("  time\n");
 	
 	calendar_tm_p = localtime ( &calendar );
 	if (debug) printf("  calendar\n");
 	
 	strftime(calendar_s,128,"%b %d %X %Z %Y\0",calendar_tm_p);
 	if (debug) printf("  strftime\n");
 	
 	fprintf(ofp,"HBPLUS Hydrogen Bond Calculator v %s            %s\n",VERSION,calendar_s );
 	fprintf(ofp,"(c) I McDonald, D Naylor, D Jones and J Thornton 1993 All Rights Reserved.\n");
 	fprintf(ofp,"Citing HBPLUS in publications that use these results is condition of use.\n");
 	fprintf(ofp,"%4.4s <- Brookhaven Code \"%s\" <- PDB file\n",brcode,fname);
 	
 	fprintf(ofp,"<---DONOR---> <-ACCEPTOR-->    atom                        ^               \n");
 	fprintf(ofp,"c    i                          cat <-CA-CA->   ^        H-A-AA   ^      H- \n");
 	fprintf(ofp,"h    n   atom  resd res      DA  || num        DHA   H-A  angle D-A-AA Bond\n");
 	fprintf(ofp,"n    s   type  num  typ     dist DA aas  dist angle  dist       angle   num\n");
 	/*
	   <---DONOR---> <-ACCEPTOR-->    atom                        ^               
	   c    i                          cat <-CA-CA->   ^        H-A-AA   ^      H- 
	   h    n   atom  resd res      DA  ||   num      DHA   H-A  angle D-A-AA Bond
	   n    s   type  num  typ     dist DA aas  dist angle  dist       angle   num
	   E0010-LEU N   E0006-TYR O   3.07 MM   4  6.17 157.2  2.13 147.8 154.9    17
	   */
    }
    
    /* First Pass : Check for disulphide bridges */
    
    
    puts("Checking for hydrogen bonds . . . ");
    
    for (ii = 0; ii < (natoms-1); ii++)
    {
	/* ignore atom incapable of H-bonding immediately */
	if (atom[ii].aacode <TOTNAA &&
	    donors[atom[ii].aacode][atom[ii].atmtyp] == 0 &&
	    accepts[atom[ii].aacode][atom[ii].atmtyp] == 0)
	    if (!nnbflg)
 		continue;
	for (jj = ii + 1; jj < natoms; jj++)
	{
 	    debug=0;
 	    
 	    if (atom[jj].aacode <TOTNAA &&
		donors[atom[jj].aacode][atom[jj].atmtyp] == 0 &&
		accepts[atom[jj].aacode][atom[jj].atmtyp] == 0)
		if (!nnbflg)
 		    continue;
	    
 	    /* if the exchangeflg has been set to 2 by the -X option, only
 	       do the hydrogen bonds for the His, Asn, and Gln side-chains */
 	    if (exchangeflg==2)
 		if ( !( (atom[ii].atmtyp > 4 && (atom[ii].aacode == His 
						 || atom[ii].aacode == Asn || atom[ii].aacode == Gln) ) 
		       || ( atom[jj].atmtyp > 4 && (atom[jj].aacode == Asn 
 		    || atom[jj].aacode == Gln || atom[jj].aacode == His) ) 
		       ) )
 		    continue;
 	    
	    /* ignore very distant atom pairs immediately */
	    if (fabs(atom[ii].p.x - atom[jj].p.x) > HBDIST || 
		fabs(atom[ii].p.y - atom[jj].p.y) > HBDIST || 
		fabs(atom[ii].p.z - atom[jj].p.z) > HBDIST )
	    {
		if (debug == 2)
		    printf("                      very distant, ignoring this pair!\n");
		continue;
	    }
	    
	    
	    /* Check each IJ atom pair twice. I.e. check for I(don) / J(acc) 
	       and J(don) / I(acc) */
	    for (k = (nnbflg)?1:0; k < 2; k++) /* slightly opaque this one */
 		/* if nnbflg is set, then this loop only executes once,
 		   because it doesn't matter which is the donor and which is
 		   the acceptor */
	    {
		if (debug == 2)
		    printf("   k = %1d\n",k);
		/* Load/swap for correct donor/acceptor order */
		if (k)
		{
		    i = jj;
		    j = ii;
		}
		else
		{
		    i = ii;
		    j = jj;
		}
		
/*		if (!strncmp(atomid(i,buf1),"6XIA/-0002-HOH O  ",10) ||
		    !strncmp(atomid(i,buf2),"6XIA/-0038-SER OG ",10) )
				debug=2;
				else
				debug=0;*//*debug setting line*/
 		if (debug == 2)
 		    printf("Checking between %s and %s.\n",atomid(i,buf1),atomid(j,buf2));
 		
 		if( is_donacc(i,j) )
		{
		    if (debug==2)
			printf(". . . are Donor/Acceptor pair.\n");
		    
		    if( calc_hb(output_string,i,j))
		    {
			fprintf_hb(output_string,i,j);
			if (debug==2)
			    printf(". . . are H-Bonded.\n");
			
		    }
		    else
			if(debug==2)
			    printf(". . . but fail the calc_hb test\n");
		    
		}
		else
		    if (debug==2)
			printf(". . . NOT Donor/Acceptor pair.\n");
		
	    } /* end k loop */
 	}     /* end jj loop */
    }         /* end ii loop */
    if (nnbflg)
	printf("%d neighbour interactions found.\n", nhb);
    else
 	printf("%d hydrogen bonds found.\n", nhb);
}
Example #24
0
/*@ -compdestroy @*/
int main(int argc, char **argv)
{
    char buf[4096];
    bool timestamp = false;
    char *format = "%F %T";
    char tmstr[200];
    bool daemonize = false;
    bool binary = false;
    bool sleepy = false;
    bool new_line = true;
    bool raw = false;
    bool watch = false;
    bool profile = false;
    int option_u = 0;                   // option to show uSeconds
    long count = -1;
    int option;
    unsigned int vflag = 0, l = 0;
    FILE *fp;
    unsigned int flags;
    fd_set fds;

    struct fixsource_t source;
    char *serialport = NULL;
    char *outfile = NULL;

    /*@-branchstate@*/
    flags = WATCH_ENABLE;
    while ((option = getopt(argc, argv, "?dD:lhrRwStT:vVn:s:o:pPu2")) != -1) {
	switch (option) {
	case 'D':
	    debug = atoi(optarg);
#ifdef CLIENTDEBUG_ENABLE
	    gps_enable_debug(debug, stderr);
#endif /* CLIENTDEBUG_ENABLE */
	    break;
	case 'n':
	    count = strtol(optarg, 0, 0);
	    break;
	case 'r':
	    raw = true;
	    /*
	     * Yes, -r invokes NMEA mode rather than proper raw mode.
	     * This emulates the behavior under the old protocol.
	     */
	    flags |= WATCH_NMEA;
	    break;
	case 'R':
	    flags |= WATCH_RAW;
	    binary = true;
	    break;
	case 'd':
	    daemonize = true;
	    break;
	case 'l':
	    sleepy = true;
	    break;
	case 't':
	    timestamp = true;
	    break;
	case 'T':
	    timestamp = true;
	    format = optarg;
	    break;
	case 'u':
	    timestamp = true;
	    option_u++;
	    break;
	case 'v':
	    vflag++;
	    break;
	case 'w':
	    flags |= WATCH_JSON;
	    watch = true;
	    break;
	case 'S':
	    flags |= WATCH_SCALED;
	    break;
	case 'p':
	    profile = true;
	    break;
	case 'P':
	    flags |= WATCH_PPS;
	    break;
	case 'V':
	    (void)fprintf(stderr, "%s: %s (revision %s)\n",
			  argv[0], VERSION, REVISION);
	    exit(EXIT_SUCCESS);
	case 's':
	    serialport = optarg;
	    break;
	case 'o':
	    outfile = optarg;
	    break;
	case '2':
	    flags |= WATCH_SPLIT24;
	    break;
	case '?':
	case 'h':
	default:
	    usage();
	    exit(EXIT_FAILURE);
	}
    }
    /*@+branchstate@*/

    /* Grok the server, port, and device. */
    if (optind < argc) {
	gpsd_source_spec(argv[optind], &source);
    } else
	gpsd_source_spec(NULL, &source);

    if (serialport != NULL && !raw) {
	(void)fprintf(stderr, "gpspipe: use of '-s' requires '-r'.\n");
	exit(EXIT_FAILURE);
    }

    if (outfile == NULL && daemonize) {
	(void)fprintf(stderr, "gpspipe: use of '-d' requires '-o'.\n");
	exit(EXIT_FAILURE);
    }

    if (!raw && !watch && !binary) {
	(void)fprintf(stderr,
		      "gpspipe: one of '-R', '-r', or '-w' is required.\n");
	exit(EXIT_FAILURE);
    }

    /* Daemonize if the user requested it. */
    /*@ -unrecog @*/
    if (daemonize)
	if (daemon(0, 0) != 0)
	    (void)fprintf(stderr,
			  "gpspipe: demonization failed: %s\n",
			  strerror(errno));
    /*@ +unrecog @*/

    /* Sleep for ten seconds if the user requested it. */
    if (sleepy)
	(void)sleep(10);

    /* Open the output file if the user requested it.  If the user
     * requested '-R', we use the 'b' flag in fopen() to "do the right
     * thing" in non-linux/unix OSes. */
    if (outfile == NULL) {
	fp = stdout;
    } else {
	if (binary)
	    fp = fopen(outfile, "wb");
	else
	    fp = fopen(outfile, "w");

	if (fp == NULL) {
	    (void)fprintf(stderr,
			  "gpspipe: unable to open output file:  %s\n",
			  outfile);
	    exit(EXIT_FAILURE);
	}
    }

    /* Open the serial port and set it up. */
    if (serialport)
	open_serial(serialport);

    /*@ -nullpass -onlytrans @*/
    if (gps_open(source.server, source.port, &gpsdata) != 0) {
	(void)fprintf(stderr,
		      "gpspipe: could not connect to gpsd %s:%s, %s(%d)\n",
		      source.server, source.port, gps_errstr(errno), errno);
	exit(EXIT_FAILURE);
    }
    /*@ +nullpass +onlytrans @*/

    if (profile)
	flags |= WATCH_TIMING;
    if (source.device != NULL)
	flags |= WATCH_DEVICE;
    (void)gps_stream(&gpsdata, flags, source.device);

    if ((isatty(STDERR_FILENO) == 0) || daemonize)
	vflag = 0;

    for (;;) {
	int r = 0;
	struct timeval tv;

	tv.tv_sec = 0;
	tv.tv_usec = 100000;
	FD_ZERO(&fds);
	FD_SET(gpsdata.gps_fd, &fds);
	errno = 0;
	r = select(gpsdata.gps_fd+1, &fds, NULL, NULL, &tv);
	if (r == -1 && errno != EINTR) {
	    (void)fprintf(stderr, "gpspipe: select error %s(%d)\n",
			  strerror(errno), errno);
	    exit(EXIT_FAILURE);
	} else if (r == 0)
		continue;

	if (vflag)
	    spinner(vflag, l++);

	/* reading directly from the socket avoids decode overhead */
	errno = 0;
	r = (int)read(gpsdata.gps_fd, buf, sizeof(buf));
	if (r > 0) {
	    int i = 0;
	    int j = 0;
	    for (i = 0; i < r; i++) {
		char c = buf[i];
		if (j < (int)(sizeof(serbuf) - 1)) {
		    serbuf[j++] = buf[i];
		}
		if (new_line && timestamp) {
		    char tmstr_u[20];            // time with "usec" resolution
		    struct timeval now;
		    struct tm *tmp_now;

		    (void)gettimeofday( &now, NULL );
		    tmp_now = localtime((time_t *)&(now.tv_sec));
		    (void)strftime(tmstr, sizeof(tmstr), format, tmp_now);
		    new_line = 0;

		    switch( option_u ) {
		    case 2:
			(void)snprintf(tmstr_u, sizeof(tmstr_u), 
				       " %ld.%06ld", now.tv_sec, now.tv_usec);
			break;
		    case 1:
			(void)snprintf(tmstr_u, sizeof(tmstr_u), 
				       ".%06ld", now.tv_usec);
			break;
		    default:
			*tmstr_u = '\0';
			break;
		    }

		    if (fprintf(fp, "%.24s%s: ", tmstr, tmstr_u) <= 0) {
			(void)fprintf(stderr,
				      "gpspipe: write error, %s(%d)\n",
				      strerror(errno), errno);
			exit(EXIT_FAILURE);
		    }
		}
		if (fputc(c, fp) == EOF) {
		    fprintf(stderr, "gpspipe: Write Error, %s(%d)\n",
			    strerror(errno), errno);
		    exit(EXIT_FAILURE);
		}

		if (c == '\n') {
		    if (serialport != NULL) {
			if (write(fd_out, serbuf, (size_t) j) == -1) {
			    fprintf(stderr,
				    "gpspipe: Serial port write Error, %s(%d)\n",
				    strerror(errno), errno);
			    exit(EXIT_FAILURE);
			}
			j = 0;
		    }

		    new_line = true;
		    /* flush after every good line */
		    if (fflush(fp)) {
			(void)fprintf(stderr,
				      "gpspipe: fflush Error, %s(%d)\n",
				      strerror(errno), errno);
			exit(EXIT_FAILURE);
		    }
		    if (count > 0) {
			if (0 >= --count) {
			    /* completed count */
			    exit(EXIT_SUCCESS);
			}
		    }
		}
	    }
	} else {
	    if (r == -1) {
		if (errno == EAGAIN)
		    continue;
		else
		    (void)fprintf(stderr, "gpspipe: read error %s(%d)\n",
			      strerror(errno), errno);
		exit(EXIT_FAILURE);
	    } else {
		exit(EXIT_SUCCESS);
	    }
	}
    }

#ifdef __UNUSED__
    if (serialport != NULL) {
	/* Restore the old serial port settings. */
	if (tcsetattr(fd_out, TCSANOW, &oldtio) != 0) {
	    (void)fprintf(stderr, "Error restoring serial port settings\n");
	    exit(EXIT_FAILURE);
	}
    }
#endif /* __UNUSED__ */

    exit(EXIT_SUCCESS);
}
Example #25
0
/**
 * @short Transforms a time_t to a ISO date string
 * 
 * The dest pointer must be at least 21 bytes long as thats the maximum size of the date.
 */
void onion_shortcut_date_string_iso(time_t t, char *dest){
	struct tm ts;
	gmtime_r(&t, &ts);
	strftime(dest, t, "%FT%TZ", &ts);
}
Example #26
0
static int
test_merge_conflicts ()
{
    SeafRepo *repo;
    char *head, *remote;
    char *file_a, *file_b, *file_bb, *file_c, *file_d, *file_e, *file_f;
    FILE *fp_a, *fp_b, *fp_c, *fp_d;
    GError *error = NULL;
    char cmd[1024];
    int ret;
    char buf[64];

    printf ("\n=== test merge conflicts\n\n");

    repo = create_repo ("merge-conflicts");

    first_commit (repo);

    sleep (2);

    printf ("*** creating branch \"test\"\n");
    /* create branch "test". */
    if (seafile_branch_add (repo->id, "test", NULL, &error) < 0) {
        fprintf (stderr, "Failed to create branch: %s.\n", error->message);
        return -1;
    }

    /* create a new commit on branch "local". */

    file_a = g_build_filename (repo->worktree, "test-a", NULL);
    file_b = g_build_filename (repo->worktree, "test-b", NULL);
    file_bb = g_build_filename (repo->worktree, "test-b/b", NULL);
    file_c = g_build_filename (repo->worktree, "c/test-c", NULL);
    file_d = g_build_filename (repo->worktree, "a", NULL);
    file_e = g_build_filename (repo->worktree, "golden-gate.jpg", NULL);
    file_f = g_build_filename (repo->worktree, "a/stanford-cs.jpg", NULL);

    /* modify an existing file, to test modify/modify conflict. */
    fp_a = g_fopen (file_a, "wb");
    if (!fp_a) {
        fprintf (stderr, "Failed to open %s: %s\n", file_a, strerror(errno));
        return -1;
    }
    fprintf (fp_a, "xyzxyz\nxyzxyz");
    fclose (fp_a);

    /* delete a file and create a directory with the same name,
     * to test d/f conflict.
     */
    g_unlink (file_b);

    if (g_mkdir (file_b, 0777) < 0) {
        fprintf (stderr, "Failed to create %s: %s\n", file_b, strerror(errno));
        return -1;
    }
    fp_b = g_fopen (file_bb, "w+b");
    if (!fp_b) {
        fprintf (stderr, "Failed to open %s: %s\n", file_bb, strerror(errno));
        return -1;
    }
    fprintf (fp_b, "1234\n1234\n");
    fclose (fp_b);

    /* modify another file, to test modify/delete conflict. */
    fp_c = g_fopen (file_c, "wb");
    if (!fp_c) {
        fprintf (stderr, "Failed to open %s: %s\n", file_c, strerror(errno));
        return -1;
    }
    fprintf (fp_c, "something else.\n");
    fclose (fp_c);

    /* delete a directory and create a file with the same name,
     * to test d/f conflict.
     */
    snprintf (cmd, 1024, "rm -r %s", file_d);
    ret = system (cmd);
    if (ret < 0 || WEXITSTATUS(ret) != 0) {
        fprintf (stderr, "Failed to remove %s\n", file_d);
        return -1;
    }
    fp_d = g_fopen (file_d, "w+b");
    if (!fp_d) {
        fprintf (stderr, "Failed to open %s: %s\n", file_d, strerror(errno));
        return -1;
    }
    fprintf (fp_d, "1234\n1234\n");
    fclose (fp_d);

    sleep (2);

    if (seaf_repo_index_add (repo, "") < 0) {
        fprintf (stderr, "Failed to add on branch local\n");
        return -1;
    }

    printf ("*** creating new commit on local\n");
    head = seaf_repo_index_commit (repo, "merge test 1.", FALSE, NULL, &error);
    if (!head) {
        fprintf (stderr, "Failed to commit on branch test\n");
        return -1;
    }

    printf ("*** checking out branch test.\n");
    /* switch to branch "test". */
    if (seafile_checkout (repo->id, "test", &error) < 0) {
        fprintf (stderr, "Failed to checkout branch test\n");
        fprintf (stderr, "Checkout error messages:\n%s", error->message);
        return -1;
    }

    sleep (2);

    /* create a new commit on branch "test". */

    /* modify/modify conflict. */
    fp_a = g_fopen (file_a, "w+b");
    if (!fp_a) {
        fprintf (stderr, "Failed to open %s: %s\n", file_a, strerror(errno));
        return -1;
    }
    fprintf (fp_a, "abcabc\nabcabc");
    fclose (fp_a);

    /* df conflict occurs only when files are changed. */
    fp_b = g_fopen (file_b, "wb");
    if (!fp_b) {
        fprintf (stderr, "Failed to open %s: %s\n", file_b, strerror(errno));
        return -1;
    }
    fprintf (fp_b, "12345678");
    fclose (fp_b);    

    /* modify/delete conflict. */
    g_unlink (file_c);

    /* df conflict occurs only when files are changed. */
    snprintf (cmd, 1024, "cp %s %s", file_e, file_f);
    ret = system (cmd);
    if (ret < 0 || WEXITSTATUS(ret) != 0) {
        fprintf (stderr, "Failed to cp %s to %s\n", file_e, file_f);
        return -1;
    }

    sleep (2);

    if (seaf_repo_index_add (repo, "") < 0) {
        fprintf (stderr, "Failed to add on branch test\n");
        return -1;
    }

    printf ("*** creating new commit on branch test.\n");
    remote = seaf_repo_index_commit (repo, "merge test 2.", FALSE, NULL, &error);
    if (!remote) {
        fprintf (stderr, "Failed to commit on branch test\n");
        return -1;
    }

    printf ("*** checking out branch local.\n");
    /* switch back to branch "local". */
    if (seafile_checkout (repo->id, "local", &error) < 0) {
        fprintf (stderr, "Failed to checkout branch local\n");
        fprintf (stderr, "Checkout error messages:\n%s", error->message);
        return -1;
    }

    sleep (2);

    printf ("*** merging test to local.\n");
    /* merge branch "test". */
    if (seafile_merge (repo->id, "test", &error) == 0) {
        fprintf (stderr, "This merge is supposed to fail!!\n");
        return -1;
    }
    fprintf (stderr, "Merge error messages:\n%s", error->message);

    printf ("*** check merge conflict results.\n");

    if (g_access (file_f, F_OK) != 0) {
        fprintf (stderr, "Bug: %s should exist.\n", file_a);
        return -1;
    }

    if (g_access (file_c, F_OK) != 0) {
        fprintf (stderr, "Bug: %s should exist.\n", file_c);
        return -1;
    }
	time_t t = time(NULL);
	strftime(buf, 64, "--plt_%Y-%m-%d", localtime(&t));

    char *file_a_local = g_strconcat (file_a, buf, NULL);
    char *file_a_test = g_strconcat (file_a, "", NULL);
    if (check_file_content (file_a_local, "xyzxyz\nxyzxyz", 13) < 0)
        return -1;
    if (check_file_content (file_a_test, "abcabc\nabcabc", 13) < 0)
        return -1;

    char *file_d_local = g_strconcat (file_d, buf, NULL);
    if (check_file_content (file_d_local, "1234\n1234\n", 10) < 0)
        return -1;
    if (check_dir (file_d) < 0) {
        return -1;
    }

    char *dir_b_test = g_strconcat (file_b, buf, NULL);
    if (check_file_content (file_b, "12345678", 8) < 0)
        return -1;
    if (check_dir (dir_b_test) < 0) {
        return -1;
    }

    printf ("\n=== Successfully handle merge conflict.\n\n");
    return 0;
}
Example #27
0
int
lws_http_action(struct lws *wsi)
{
	struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
	enum http_connection_type connection_type;
	enum http_version request_version;
	char content_length_str[32];
	const struct lws_http_mount *hm, *hit = NULL;
	unsigned int n, count = 0;
	char http_version_str[10];
	char http_conn_str[20];
	int http_version_len;
	char *uri_ptr = NULL;
	int uri_len = 0, best = 0;
	int meth = -1;

	static const unsigned char methods[] = {
		WSI_TOKEN_GET_URI,
		WSI_TOKEN_POST_URI,
		WSI_TOKEN_OPTIONS_URI,
		WSI_TOKEN_PUT_URI,
		WSI_TOKEN_PATCH_URI,
		WSI_TOKEN_DELETE_URI,
#ifdef LWS_USE_HTTP2
		WSI_TOKEN_HTTP_COLON_PATH,
#endif
	};
#if defined(_DEBUG) || defined(LWS_WITH_ACCESS_LOG)
	static const char * const method_names[] = {
		"GET", "POST", "OPTIONS", "PUT", "PATCH", "DELETE",
#ifdef LWS_USE_HTTP2
		":path",
#endif
	};
#endif

	/* it's not websocket.... shall we accept it as http? */

	for (n = 0; n < ARRAY_SIZE(methods); n++)
		if (lws_hdr_total_length(wsi, methods[n]))
			count++;
	if (!count) {
		lwsl_warn("Missing URI in HTTP request\n");
		goto bail_nuke_ah;
	}

	if (count != 1) {
		lwsl_warn("multiple methods?\n");
		goto bail_nuke_ah;
	}

	if (lws_ensure_user_space(wsi))
		goto bail_nuke_ah;

	for (n = 0; n < ARRAY_SIZE(methods); n++)
		if (lws_hdr_total_length(wsi, methods[n])) {
			uri_ptr = lws_hdr_simple_ptr(wsi, methods[n]);
			uri_len = lws_hdr_total_length(wsi, methods[n]);
			lwsl_info("Method: %s request for '%s'\n",
				  	method_names[n], uri_ptr);
			meth = n;
			break;
		}

	(void)meth;

	/* we insist on absolute paths */

	if (uri_ptr[0] != '/') {
		lws_return_http_status(wsi, HTTP_STATUS_FORBIDDEN, NULL);

		goto bail_nuke_ah;
	}

	/* HTTP header had a content length? */

	wsi->u.http.content_length = 0;
	if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI) ||
		lws_hdr_total_length(wsi, WSI_TOKEN_PATCH_URI) ||
		lws_hdr_total_length(wsi, WSI_TOKEN_PUT_URI))
		wsi->u.http.content_length = 100 * 1024 * 1024;

	if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH)) {
		lws_hdr_copy(wsi, content_length_str,
			     sizeof(content_length_str) - 1,
			     WSI_TOKEN_HTTP_CONTENT_LENGTH);
		wsi->u.http.content_length = atoi(content_length_str);
	}

	if (wsi->http2_substream) {
		wsi->u.http.request_version = HTTP_VERSION_2;
	} else {
		/* http_version? Default to 1.0, override with token: */
		request_version = HTTP_VERSION_1_0;

		/* Works for single digit HTTP versions. : */
		http_version_len = lws_hdr_total_length(wsi, WSI_TOKEN_HTTP);
		if (http_version_len > 7) {
			lws_hdr_copy(wsi, http_version_str,
					sizeof(http_version_str) - 1, WSI_TOKEN_HTTP);
			if (http_version_str[5] == '1' && http_version_str[7] == '1')
				request_version = HTTP_VERSION_1_1;
		}
		wsi->u.http.request_version = request_version;

		/* HTTP/1.1 defaults to "keep-alive", 1.0 to "close" */
		if (request_version == HTTP_VERSION_1_1)
			connection_type = HTTP_CONNECTION_KEEP_ALIVE;
		else
			connection_type = HTTP_CONNECTION_CLOSE;

		/* Override default if http "Connection:" header: */
		if (lws_hdr_total_length(wsi, WSI_TOKEN_CONNECTION)) {
			lws_hdr_copy(wsi, http_conn_str, sizeof(http_conn_str) - 1,
				     WSI_TOKEN_CONNECTION);
			http_conn_str[sizeof(http_conn_str) - 1] = '\0';
			if (!strcasecmp(http_conn_str, "keep-alive"))
				connection_type = HTTP_CONNECTION_KEEP_ALIVE;
			else
				if (!strcasecmp(http_conn_str, "close"))
					connection_type = HTTP_CONNECTION_CLOSE;
		}
		wsi->u.http.connection_type = connection_type;
	}

	n = wsi->protocol->callback(wsi, LWS_CALLBACK_FILTER_HTTP_CONNECTION,
				    wsi->user_space, uri_ptr, uri_len);
	if (n) {
		lwsl_info("LWS_CALLBACK_HTTP closing\n");

		return 1;
	}
	/*
	 * if there is content supposed to be coming,
	 * put a timeout on it having arrived
	 */
	lws_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT,
			wsi->context->timeout_secs);
#ifdef LWS_OPENSSL_SUPPORT
	if (wsi->redirect_to_https) {
		/*
		 * we accepted http:// only so we could redirect to
		 * https://, so issue the redirect.  Create the redirection
		 * URI from the host: header and ignore the path part
		 */
		unsigned char *start = pt->serv_buf + LWS_PRE, *p = start,
			      *end = p + 512;

		if (!lws_hdr_total_length(wsi, WSI_TOKEN_HOST))
			goto bail_nuke_ah;

		n = sprintf((char *)end, "https://%s/",
			    lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST));

		n = lws_http_redirect(wsi, HTTP_STATUS_MOVED_PERMANENTLY,
				      end, n, &p, end);
		if ((int)n < 0)
			goto bail_nuke_ah;

		return lws_http_transaction_completed(wsi);
	}
#endif

#ifdef LWS_WITH_ACCESS_LOG
	/*
	 * Produce Apache-compatible log string for wsi, like this:
	 *
	 * 2.31.234.19 - - [27/Mar/2016:03:22:44 +0800]
	 * "GET /aep-screen.png HTTP/1.1"
	 * 200 152987 "https://libwebsockets.org/index.html"
	 * "Mozilla/5.0 (Macint... Chrome/49.0.2623.87 Safari/537.36"
	 *
	 */
	{
		static const char * const hver[] = {
			"http/1.0", "http/1.1", "http/2"
		};
#ifdef LWS_USE_IPV6
		char ads[INET6_ADDRSTRLEN];
#else
		char ads[INET_ADDRSTRLEN];
#endif
		char da[64];
		const char *pa, *me;
		struct tm *tmp;
		time_t t = time(NULL);
		int l = 256;

		if (wsi->access_log_pending)
			lws_access_log(wsi);

		wsi->access_log.header_log = lws_malloc(l);

		tmp = localtime(&t);
		if (tmp)
			strftime(da, sizeof(da), "%d/%b/%Y:%H:%M:%S %z", tmp);
		else
			strcpy(da, "01/Jan/1970:00:00:00 +0000");

		pa = lws_get_peer_simple(wsi, ads, sizeof(ads));
		if (!pa)
			pa = "(unknown)";

		if (meth >= 0)
			me = method_names[meth];
		else
			me = "unknown";

		snprintf(wsi->access_log.header_log, l,
			 "%s - - [%s] \"%s %s %s\"",
			 pa, da, me, uri_ptr,
			 hver[wsi->u.http.request_version]);

		l = lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_USER_AGENT);
		if (l) {
			wsi->access_log.user_agent = lws_malloc(l + 2);
			lws_hdr_copy(wsi, wsi->access_log.user_agent,
				     l + 1, WSI_TOKEN_HTTP_USER_AGENT);
		}
		wsi->access_log_pending = 1;
	}
#endif

	/* can we serve it from the mount list? */

	hm = wsi->vhost->mount_list;
	while (hm) {
		if (uri_len >= hm->mountpoint_len &&
		    !strncmp(uri_ptr, hm->mountpoint, hm->mountpoint_len) &&
		    (uri_ptr[hm->mountpoint_len] == '\0' ||
		     uri_ptr[hm->mountpoint_len] == '/' ||
		     hm->mountpoint_len == 1)
		    ) {
			if (hm->origin_protocol == LWSMPRO_CALLBACK ||
			    ((hm->origin_protocol == LWSMPRO_CGI ||
			     lws_hdr_total_length(wsi, WSI_TOKEN_GET_URI)) &&
			    hm->mountpoint_len > best)) {
				best = hm->mountpoint_len;
				hit = hm;
			}
		}
		hm = hm->mount_next;
	}
	if (hit) {
		char *s = uri_ptr + hit->mountpoint_len;

		lwsl_debug("*** hit %d %d %s\n", hit->mountpoint_len,
			   hit->origin_protocol , hit->origin);

		/*
		 * if we have a mountpoint like https://xxx.com/yyy
		 * there is an implied / at the end for our purposes since
		 * we can only mount on a "directory".
		 *
		 * But if we just go with that, the browser cannot understand
		 * that he is actually looking down one "directory level", so
		 * even though we give him /yyy/abc.html he acts like the
		 * current directory level is /.  So relative urls like "x.png"
		 * wrongly look outside the mountpoint.
		 *
		 * Therefore if we didn't come in on a url with an explicit
		 * / at the end, we must redirect to add it so the browser
		 * understands he is one "directory level" down.
		 */
		if ((hit->mountpoint_len > 1 ||
		     (hit->origin_protocol == LWSMPRO_REDIR_HTTP ||
		      hit->origin_protocol == LWSMPRO_REDIR_HTTPS)) &&
		    (*s != '/' ||
		     (hit->origin_protocol == LWSMPRO_REDIR_HTTP ||
		      hit->origin_protocol == LWSMPRO_REDIR_HTTPS)) &&
		    (hit->origin_protocol != LWSMPRO_CGI && hit->origin_protocol != LWSMPRO_CALLBACK)) {
			unsigned char *start = pt->serv_buf + LWS_PRE,
					      *p = start, *end = p + 512;
			static const char *oprot[] = {
				"http://", "https://"
			};

			lwsl_debug("Doing 301 '%s' org %s\n", s, hit->origin);

			if (!lws_hdr_total_length(wsi, WSI_TOKEN_HOST))
				goto bail_nuke_ah;

			/* > at start indicates deal with by redirect */
			if (hit->origin_protocol & 4)
				n = snprintf((char *)end, 256, "%s%s",
					    oprot[hit->origin_protocol & 1],
					    hit->origin);
			else
				n = snprintf((char *)end, 256,
				    "https://%s/%s/",
				    lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST),
				    uri_ptr);

			n = lws_http_redirect(wsi, HTTP_STATUS_MOVED_PERMANENTLY,
					      end, n, &p, end);
			if ((int)n < 0)
				goto bail_nuke_ah;

			return lws_http_transaction_completed(wsi);
		}

		/*
		 * A particular protocol callback is mounted here?
		 *
		 * For the duration of this http transaction, bind us to the
		 * associated protocol
		 */
		if (hit->origin_protocol == LWSMPRO_CALLBACK) {

			for (n = 0; n < wsi->vhost->count_protocols; n++)
				if (!strcmp(wsi->vhost->protocols[n].name,
					   hit->origin)) {

					if (wsi->protocol != &wsi->vhost->protocols[n])
						if (!wsi->user_space_externally_allocated)
							lws_free_set_NULL(wsi->user_space);
					wsi->protocol = &wsi->vhost->protocols[n];
					if (lws_ensure_user_space(wsi)) {
						lwsl_err("Unable to allocate user space\n");

						return 1;
					}
					break;
				}

			if (n == wsi->vhost->count_protocols) {
				n = -1;
				lwsl_err("Unable to find plugin '%s'\n",
					 hit->origin);
			}

			n = wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP,
						    wsi->user_space, uri_ptr, uri_len);

			goto after;
		}

		/* deferred cleanup and reset to protocols[0] */

		if (wsi->protocol != &wsi->vhost->protocols[0])
			if (!wsi->user_space_externally_allocated)
				lws_free_set_NULL(wsi->user_space);

		wsi->protocol = &wsi->vhost->protocols[0];

#ifdef LWS_WITH_CGI
		/* did we hit something with a cgi:// origin? */
		if (hit->origin_protocol == LWSMPRO_CGI) {
			const char *cmd[] = {
				NULL, /* replace with cgi path */
				NULL
			};
			unsigned char *p, *end, buffer[256];

			lwsl_debug("%s: cgi\n", __func__);
			cmd[0] = hit->origin;

			n = 5;
			if (hit->cgi_timeout)
				n = hit->cgi_timeout;

			n = lws_cgi(wsi, cmd, hit->mountpoint_len, n,
				    hit->cgienv);
			if (n) {
				lwsl_err("%s: cgi failed\n");
				return -1;
			}
			p = buffer + LWS_PRE;
			end = p + sizeof(buffer) - LWS_PRE;

			if (lws_add_http_header_status(wsi, 200, &p, end))
				return 1;
			if (lws_add_http_header_by_token(wsi, WSI_TOKEN_CONNECTION,
					(unsigned char *)"close", 5, &p, end))
				return 1;
			n = lws_write(wsi, buffer + LWS_PRE,
				      p - (buffer + LWS_PRE),
				      LWS_WRITE_HTTP_HEADERS);

			goto deal_body;
		}
#endif

		n = strlen(s);
		if (s[0] == '\0' || (n == 1 && s[n - 1] == '/'))
			s = (char *)hit->def;
		if (!s)
			s = "index.html";

		wsi->cache_secs = hit->cache_max_age;
		wsi->cache_reuse = hit->cache_reusable;
		wsi->cache_revalidate = hit->cache_revalidate;
		wsi->cache_intermediaries = hit->cache_intermediaries;

		n = lws_http_serve(wsi, s, hit->origin);
		if (n) {
			/*
			 * 	lws_return_http_status(wsi, HTTP_STATUS_NOT_FOUND, NULL);
			 */
			n = wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP,
					    wsi->user_space, uri_ptr, uri_len);
		}
	} else {
		/* deferred cleanup and reset to protocols[0] */

		if (wsi->protocol != &wsi->vhost->protocols[0])
			if (!wsi->user_space_externally_allocated)
				lws_free_set_NULL(wsi->user_space);
		wsi->protocol = &wsi->vhost->protocols[0];

		n = wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP,
				    wsi->user_space, uri_ptr, uri_len);
	}
after:
	if (n) {
		lwsl_info("LWS_CALLBACK_HTTP closing\n");

		return 1;
	}

#ifdef LWS_WITH_CGI
deal_body:
#endif
	/*
	 * If we're not issuing a file, check for content_length or
	 * HTTP keep-alive. No keep-alive header allocation for
	 * ISSUING_FILE, as this uses HTTP/1.0.
	 *
	 * In any case, return 0 and let lws_read decide how to
	 * proceed based on state
	 */
	if (wsi->state != LWSS_HTTP_ISSUING_FILE)
		/* Prepare to read body if we have a content length: */
		if (wsi->u.http.content_length > 0)
			wsi->state = LWSS_HTTP_BODY;

	return 0;

bail_nuke_ah:
	/* we're closing, losing some rx is OK */
	wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
	lws_header_table_detach(wsi, 1);

	return 1;
}
Example #28
0
S3Status listBucketCallback(int isTruncated, const char *nextMarker,
                                   int contentsCount,
                                   const S3ListBucketContent *contents,
                                   int commonPrefixesCount,
                                   const char **commonPrefixes,
                                   void *callbackData)
{
    list_bucket_callback_data *data =
        (list_bucket_callback_data *) callbackData;

    data->isTruncated = isTruncated;
    // This is tricky.  S3 doesn't return the NextMarker if there is no
    // delimiter.  Why, I don't know, since it's still useful for paging
    // through results.  We want NextMarker to be the last content in the
    // list, so set it to that if necessary.
    if ((!nextMarker || !nextMarker[0]) && contentsCount) {
        nextMarker = contents[contentsCount - 1].key;
    }
    if (nextMarker) {
        snprintf(data->nextMarker, sizeof(data->nextMarker), "%s",
                 nextMarker);
    }
    else {
        data->nextMarker[0] = 0;
    }

//    if (contentsCount && !data->keyCount) {
//        printListBucketHeader(data->allDetails);
//    }

    int i;
    for (i = 0; i < contentsCount; i++) {
        const S3ListBucketContent *content = &(contents[i]);
        char timebuf[256];
        time_t t = (time_t) content->lastModified;
        strftime(timebuf, sizeof(timebuf), "%Y-%m-%dT%H:%M:%SZ",
                 gmtime(&t));
        char sizebuf[16];
        if (content->size < 100000) {
            sprintf(sizebuf, "%5llu", (unsigned long long) content->size);
        }
        else if (content->size < (1024 * 1024)) {
            sprintf(sizebuf, "%4lluK",
                    ((unsigned long long) content->size) / 1024ULL);
        }
        else if (content->size < (10 * 1024 * 1024)) {
            float f = content->size;
            f /= (1024 * 1024);
            sprintf(sizebuf, "%1.2fM", f);
        }
        else if (content->size < (1024 * 1024 * 1024)) {
            sprintf(sizebuf, "%4lluM",
                    ((unsigned long long) content->size) /
                    (1024ULL * 1024ULL));
        }
        else {
            float f = (content->size / 1024);
            f /= (1024 * 1024);
            sprintf(sizebuf, "%1.2fG", f);
        }
        savedContents.append(*content);
        savedKeys.append(content->key);
    }

    data->keyCount += contentsCount;

    for (i = 0; i < commonPrefixesCount; i++) {
        savedCommonPrefixes.append(commonPrefixes[i]);
    }

    return S3StatusOK;
}
int escuchaCliente(int socket, struct sockaddr_in addr)
{

    char buffer[BUFFERSIZE];
    char aux[BUFFERSIZE];
    int bytecount;
    int fin=0;
    int code=0;         /* Código de salida por defecto */
    time_t t;
    struct tm *tmp;
    socklen_t slen=sizeof(addr);
    while (!fin)
      {

    memset(buffer, 0, BUFFERSIZE);


       if((bytecount=recvfrom(socket,buffer,BUFFERSIZE,0,(struct sockaddr*)&addr,&slen))==-1)
       {
       error(5, "No puedo recibir información");
         }
printf("%s\n",buffer);
    /* Evaluamos los comandos */
    /* El sistema de gestión de comandos es muy rudimentario, pero nos vale */
    /* Comando TIME - Da la hora */
    if (strncmp(buffer, "TIME", 4)==0)
      {
        memset(buffer, 0, BUFFERSIZE);

        t = time(NULL);
        tmp = localtime(&t);
        strftime(buffer, BUFFERSIZE, "%Y-%m-%d %H:%M:%S", tmp);
      }
    
    /* Comando EXIT - Cierra la conexión actual */
    else if (strncmp(buffer, "EXIT", 4)==0)
      {
        memset(buffer, 0, BUFFERSIZE);
        sprintf(buffer, "Hasta luego. Vuelve pronto %s\n", inet_ntoa(addr.sin_addr));
        fin=1;
      }
    /* Comando CERRAR - Cierra el servidor */
    else if (strncmp(buffer, "CERRAR", 6)==0)
      {
        memset(buffer, 0, BUFFERSIZE);
        sprintf(buffer, "Adiós. Cierro el servidor\n");
        fin=1;
        code=99;        /* Salir del programa */
      }
    else
      {     
        sprintf(aux, "ECHO: %s\n", buffer);
        strcpy(buffer, aux);
      }

     if(bytecount = sendto(socket,buffer,strlen(buffer),0, (struct sockaddr*)&addr, sizeof(addr))==-1){
          error(6, "No puedo enviar información");
     }
}
 
    close(socket);
    return code;
}
Example #30
0
static apr_size_t win32_strftime_extra(char *s, size_t max, const char *format,
                                       const struct tm *tm) 
{
   /* If the new format string is bigger than max, the result string won't fit
    * anyway. If format strings are added, made sure the padding below is
    * enough */
    char *new_format = (char *) malloc(max + 11);
    size_t i, j, format_length = strlen(format);
    apr_size_t return_value;
    int length_written;

    for (i = 0, j = 0; (i < format_length && j < max);) {
        if (format[i] != '%') {
            new_format[j++] = format[i++];
            continue;
        }
        switch (format[i+1]) {
            case 'C':
                length_written = apr_snprintf(new_format + j, max - j, "%2d",
                    (tm->tm_year + 1970)/100);
                j = (length_written == -1) ? max : (j + length_written);
                i += 2;
                break;
            case 'D':
                /* Is this locale dependent? Shouldn't be...
                   Also note the year 2000 exposure here */
                memcpy(new_format + j, "%m/%d/%y", 8);
                i += 2;
                j += 8;
                break;
            case 'r':
                memcpy(new_format + j, "%I:%M:%S %p", 11);
                i += 2;
                j += 11;
                break;
            case 'R':
                memcpy(new_format + j, "%H:%M", 5);
                i += 2;
                j += 5;
                break;
            case 'T':
                memcpy(new_format + j, "%H:%M:%S", 8);
                i += 2;
                j += 8;
                break;
            case 'e':
                length_written = apr_snprintf(new_format + j, max - j, "%2d",
                    tm->tm_mday);
                j = (length_written == -1) ? max : (j + length_written);
                i += 2;
                break;
            default:
                /* We know we can advance two characters forward here. Also
                 * makes sure that %% is preserved. */
                new_format[j++] = format[i++];
                new_format[j++] = format[i++];
        }
    }
    if (j >= max) {
        *s = '\0';  /* Defensive programming, okay since output is undefined*/
        return_value = 0;
    } else {
        new_format[j] = '\0';
        return_value = strftime(s, max, new_format, tm);
    }
    free(new_format);
    return return_value;
}