/**
 * @stmtsort_init_output: get temporary file name for sort output.
 *
 * @return:
 *	< 0	: success.
 *	< !0	: fail.
 */
int stmtsort_init_output(struct Stmt *sort)
{
	int		s;
	char		*rndm_name	= 0;
	struct String	*tmp		= 0;

	/* filename already declared by INTO statement */
	if (sort->out->filename)
		return 0;

	str_create(&tmp);

	do {
		str_append(tmp, get_tmp_dir(0));

		s = str_raw_randomize(VOS_SORT_OUT_FORMAT, &rndm_name);
		if (s)
			goto err;

		str_append(tmp, rndm_name);

		s = file_raw_is_exist(tmp->buf);
		if (s)
			str_prune(tmp);

		free(rndm_name);
	} while (s);

	sort->out->flag		|= SORT_TMP;
	sort->out->filename	= tmp->buf;
	tmp->buf		= 0;
err:
	str_destroy(&tmp);
	return s;
}
Exemple #2
0
char *get_tmp_dir_filename(char *dest, size_t destlen, const char *filename)
{
	char *tmp_dir = get_tmp_dir();
	const char *slash = "/";
	if(tmp_dir[strlen(tmp_dir) - 1] == '/') { slash = ""; }
	snprintf(dest, destlen, "%s%s%s", tmp_dir, slash, filename);
	return dest;
}
Exemple #3
0
gint news_cancel_article(Folder * folder, MsgInfo * msginfo)
{
	gchar * tmp;
	FILE * tmpfp;
	gchar buf[BUFFSIZE];

	tmp = g_strdup_printf("%s%ccancel%p", get_tmp_dir(),
			      G_DIR_SEPARATOR, msginfo);
	if (tmp == NULL)
		return -1;

	if ((tmpfp = g_fopen(tmp, "wb")) == NULL) {
		FILE_OP_ERROR(tmp, "fopen");
		return -1;
	}
	if (change_file_mode_rw(tmpfp, tmp) < 0) {
		FILE_OP_ERROR(tmp, "chmod");
		g_warning("can't change file mode");
	}
	
	get_rfc822_date(buf, sizeof(buf));
	if (fprintf(tmpfp, "From: %s\r\n"
		       "Newsgroups: %s\r\n"
		       "Subject: cmsg cancel <%s>\r\n"
		       "Control: cancel <%s>\r\n"
		       "Approved: %s\r\n"
		       "X-Cancelled-by: %s\r\n"
		       "Date: %s\r\n"
		       "\r\n"
		       "removed with Claws Mail\r\n",
		       msginfo->from,
		       msginfo->newsgroups,
		       msginfo->msgid,
		       msginfo->msgid,
		       msginfo->from,
		       msginfo->from,
		       buf) < 0) {
		FILE_OP_ERROR(tmp, "fprintf");
		fclose(tmpfp);
		claws_unlink(tmp);
		g_free(tmp);
		return -1;
	}

	if (fclose(tmpfp) == EOF) {
		FILE_OP_ERROR(tmp, "fclose");
		claws_unlink(tmp);
		g_free(tmp);
		return -1;
	}

	news_post(folder, tmp);
	claws_unlink(tmp);

	g_free(tmp);

	return 0;
}
Exemple #4
0
char *get_pid_file(void)
{
	static char pid_file[2048];

	if (!pid_file[0])
		snprintf(pid_file, sizeof(pid_file), "%s/pid-wakeup",
			 get_tmp_dir());
	return pid_file;
}
Exemple #5
0
char *get_pipe_dir(void)
{
	static char pipe_dir[2048];

	if (!pipe_dir[0])
		snprintf(pipe_dir, sizeof(pipe_dir), "%s/event_pipe",
			 get_tmp_dir());
	return pipe_dir;
}
Exemple #6
0
static int setup_sandbox(struct sandbox_info_t *sandbox_info, bool interactive)
{
	if (NULL != getenv(ENV_PORTAGE_TMPDIR)) {
		/* Portage handle setting SANDBOX_WRITE itself. */
		sandbox_info->work_dir[0] = '\0';
	} else {
		if (NULL == getcwd(sandbox_info->work_dir, SB_PATH_MAX)) {
			sb_pwarn("failed to get current directory");
			return -1;
		}
		if (interactive)
			setenv(ENV_SANDBOX_WORKDIR, sandbox_info->work_dir, 1);
	}

	if (-1 == get_tmp_dir(sandbox_info->tmp_dir)) {
		sb_pwarn("failed to get tmp_dir");
		return -1;
	}
	setenv(ENV_TMPDIR, sandbox_info->tmp_dir, 1);

	sandbox_info->home_dir = getenv("HOME");
	if (!sandbox_info->home_dir) {
		sandbox_info->home_dir = sandbox_info->tmp_dir;
		setenv("HOME", sandbox_info->home_dir, 1);
	}

	/* Generate sandbox lib path */
	get_sandbox_lib(sandbox_info->sandbox_lib);

	/* Generate sandbox bashrc path */
	get_sandbox_rc(sandbox_info->sandbox_rc);

	/* Generate sandbox log full path */
	get_sandbox_log(sandbox_info->sandbox_log);
	if (rc_file_exists(sandbox_info->sandbox_log)) {
		if (-1 == unlink(sandbox_info->sandbox_log)) {
			sb_pwarn("could not unlink old log file: %s",
			         sandbox_info->sandbox_log);
			return -1;
		}
	}

	/* Generate sandbox debug log full path */
	get_sandbox_debug_log(sandbox_info->sandbox_debug_log);
	if (rc_file_exists(sandbox_info->sandbox_debug_log)) {
		if (-1 == unlink(sandbox_info->sandbox_debug_log)) {
			sb_pwarn("could not unlink old debug log file: %s",
			         sandbox_info->sandbox_debug_log);
			return -1;
		}
	}

	return 0;
}
Exemple #7
0
void PurpleLine::close() {
    disconnect_signals();

    if (temp_files.size()) {
        for (std::string &path: temp_files)
            g_unlink(path.c_str());

        g_rmdir(get_tmp_dir().c_str());
    }

    delete this;
}
Exemple #8
0
static void
setup_database(BenchmarkData *data)
{
  grn_ctx *context = &(data->context);
  gchar *tmp_dir;
  gchar *database_last_component_name;
  gchar *database_path;
  guint i;

  tmp_dir = get_tmp_dir();
  database_last_component_name =
    g_strdup_printf("db-%d-%s-mruby",
                    data->n_records,
                    data->use_mruby ? "with" : "without");
  database_path = g_build_filename(tmp_dir,
                                   "range-select",
                                   database_last_component_name,
                                   NULL);
  g_free(database_last_component_name);

  if (g_file_test(database_path, G_FILE_TEST_EXISTS)) {
    data->database = grn_db_open(context, database_path);
    run_command(context, "dump");
  } else {
    data->database = grn_db_create(context, database_path, NULL);

    run_command(context, "table_create Entries TABLE_NO_KEY");
    run_command(context, "column_create Entries rank COLUMN_SCALAR Int32");
    run_command(context, "table_create Ranks TABLE_PAT_KEY Int32");
    run_command(context,
                "column_create Ranks entries_rank COLUMN_INDEX Entries rank");

    run_command(context, "load --table Entries");
    run_command(context, "[");
    for (i = 0; i < data->n_records; i++) {
#define BUFFER_SIZE 4096
      gchar buffer[BUFFER_SIZE];
      const gchar *separator;
      if (i == (data->n_records - 1)) {
        separator = "";
      } else {
        separator = ",";
      }
      snprintf(buffer, BUFFER_SIZE, "{\"rank\": %u}%s", i, separator);
      run_command(context, buffer);
#undef BUFFER_SIZE
    }
    run_command(context, "]");
  }

  g_free(database_path);
}
static char *mkcachefile(const char *name, const char *bucket)
{
    if (name != NULL) {
        return strdup(name);
    } else {
        char buffer[1024];
        const char *tmpdir = get_tmp_dir();

        snprintf(buffer, sizeof(buffer),
                 "%s/%s", tmpdir ? tmpdir : ".", bucket);
        return strdup(buffer);
    }
}
Exemple #10
0
static void
parse_config(void)
{
  FILE *f = 0;
  struct generic_section_config *p = 0;
  const unsigned char *subst_src[10];
  const unsigned char *subst_dst[10];
  int subst_idx = 0;
  unsigned char tmp_dir[EJ_PATH_MAX];

  memset(subst_src, 0, sizeof(subst_src));
  memset(subst_dst, 0, sizeof(subst_dst));

  if (!config_file) die("configuration file is not specified");
  f = fopen(config_file, "r");
  if (!f) die("cannot open configuration file %s", config_file);
  config = parse_param(config_file, 0, params, 1, 0, 0, 0);
  if (!config) {
    exit(1);
  }
  fclose(f); f = 0;

  for (p = config; p; p = p->next) {
    if (!p->name[0] || !strcmp(p->name, "global")) {
      global = (struct config_global_data *) p;
    }
  }

  if (!global) die("no global section in configuration file %s", config_file);

  if (global->sleep_time <= 0) global->sleep_time = 1000;
  if (!global->spool_dir[0]) {
    die("spool_dir is undefined in %s", config_file);
  }
  if (!global->work_dir[0]) {
    die("work_dir is undefined in %s", config_file);
  }

  subst_src[subst_idx] = "/TMPDIR";
  subst_dst[subst_idx] = get_tmp_dir(tmp_dir, sizeof(tmp_dir));
  subst_idx++;
  param_subst(global->work_dir, sizeof(global->work_dir), subst_src, subst_dst);

  snprintf(global->queue_dir, sizeof(global->queue_dir), "%s/queue", global->spool_dir);
  snprintf(global->result_dir, sizeof(global->result_dir), "%s/result", global->spool_dir);

  printf("%d\n", global->sleep_time);
  printf("%s\n", global->spool_dir);
  printf("%s\n", global->work_dir);
  printf("%s\n", global->cache_dir);
}
Exemple #11
0
gint syl_setup_rc_dir(void)
{
	if (!is_dir_exist(get_rc_dir())) {
		if (make_dir_hier(get_rc_dir()) < 0)
			return -1;
	}

	MAKE_DIR_IF_NOT_EXIST(get_mail_base_dir());

	CHDIR_RETURN_VAL_IF_FAIL(get_rc_dir(), -1);

	MAKE_DIR_IF_NOT_EXIST(get_imap_cache_dir());
	MAKE_DIR_IF_NOT_EXIST(get_news_cache_dir());
	MAKE_DIR_IF_NOT_EXIST(get_mime_tmp_dir());
	MAKE_DIR_IF_NOT_EXIST(get_tmp_dir());
	MAKE_DIR_IF_NOT_EXIST(UIDL_DIR);
	MAKE_DIR_IF_NOT_EXIST(PLUGIN_DIR);

	/* remove temporary files */
	remove_all_files(get_tmp_dir());
	remove_all_files(get_mime_tmp_dir());

	return 0;
}
Exemple #12
0
void syl_cleanup(void)
{
	/* remove temporary files */
	remove_all_files(get_tmp_dir());
	remove_all_files(get_mime_tmp_dir());
#if GLIB_CHECK_VERSION(2, 6, 0)
	g_log_set_default_handler(g_log_default_handler, NULL);
#endif
	close_log_file();

	sock_cleanup();

	if (app) {
		g_object_unref(app);
		app = NULL;
	}
}
Exemple #13
0
int mpkgSys::build_package(string out_directory, bool source)
{

	if (source) say("Building in [%s], source package\n", out_directory.c_str());
	if (!source) say("Building in [%s], binary package\n", out_directory.c_str());

	string pkgname;
	if (out_directory.empty()) out_directory = "./";
	if (out_directory.find_last_of("/")!=out_directory.length()-1) out_directory+="/";
	string pkgType=mConfig.getValue("build_pkg_type");
	if (pkgType.empty()) pkgType="txz";
	printf("pkgType=[%s]\n", pkgType.c_str());
	if (FileNotEmpty("install/data.xml"))
    	{
	    	PackageConfig p("install/data.xml");
	    	if (!p.parseOk) 
		{
			mError("Parse error");
			return -100;
		}
		if (source)
		{
			pkgname =  p.getName()+"-"+p.getVersion()+"-"+p.getBuild();
	    		say(_("Packing source package to %s%s.spkg\n"), out_directory.c_str(), pkgname.c_str());
			string n = out_directory + p.getName()+"-"+p.getVersion()+"-"+p.getBuild()+".spkg";
			unlink(n.c_str());
			system("ls -la && tar -cf " + out_directory + p.getName()+"-"+p.getVersion()+"-"+p.getBuild()+".spkg *");
		}
		else {

			pkgname =  p.getName()+"-"+p.getVersion()+"-"+p.getArch()+"-"+p.getBuild();
			say(_("Packing binary package to %s%s.%s\n"), out_directory.c_str(), pkgname.c_str(), pkgType.c_str());
			string tmp_dir = get_tmp_dir();
			system(MAKEPKG_CMD + " " + tmp_dir + "/" + pkgname+"."+pkgType);
			say(_("Moving package to output directory...\n"));
			system("mv " + tmp_dir + "/" + pkgname+"."+pkgType + " " + out_directory);
		}
	}
	else {
		mError("No XML data, cannot build package");
		return -1;
	}
	say(_("Package was built to %s%s.%s\n"), out_directory.c_str(), pkgname.c_str(), pkgType.c_str());
    	return 0;
}
Exemple #14
0
const char *
get_home_dir (void)
{
	static char *home_dir = NULL;
	if (!home_dir)
	{
		const struct passwd *passwd = get_passwd_info ();
		if (passwd && passwd->pw_dir)
		{
			home_dir = strdup (passwd->pw_dir);
		}
		else if ( (home_dir = getenv ("HOME")) )
		{
			home_dir = strdup (home_dir);
		}
		else
		{
			home_dir = strdup (get_tmp_dir ());
		}
		on_exit (cleaner, home_dir);
	}
	return home_dir;
}
PurpleCmdRet PurpleLine::cmd_open(PurpleConversation *conv,
    const gchar *, gchar **args, gchar **error, void *)
{
    static std::map<line::ContentType::type, std::string> attachment_extensions = {
        { line::ContentType::IMAGE, ".jpg" },
        { line::ContentType::VIDEO, ".mp4" },
        { line::ContentType::AUDIO, ".mp3" },
    };

    std::string token(args[0]);

    Attachment *att = conv_attachment_get(conv, token);
    if (!att) {
        *error = g_strdup("No such attachment.");
        return PURPLE_CMD_RET_FAILED;
    }

    if (att->path != "" && g_file_test(att->path.c_str(), G_FILE_TEST_EXISTS)) {
        purple_notify_uri(conn, att->path.c_str());
        return PURPLE_CMD_RET_OK;
    }

    // Ensure there's nothing funny about the id as we're going to use it as a path element
    try {
        std::stoll(att->id);
    } catch (...) {
        *error = g_strdup("Failed to download attachment.");
        return PURPLE_CMD_RET_FAILED;
    }

    std::string ext = ".jpg";
    if (attachment_extensions.count(att->type))
        ext = attachment_extensions[att->type];

    std::string dir = get_tmp_dir(true);

    gchar *path_p = g_build_filename(
        dir.c_str(),
        (att->id + ext).c_str(),
        nullptr);

    std::string path(path_p);

    g_free(path_p);

    purple_conversation_write(
        conv,
        "",
        "Downloading attachment...",
        (PurpleMessageFlags)PURPLE_MESSAGE_SYSTEM,
        time(NULL));

    std::string url = std::string(LINE_OS_URL) + "os/m/"+ att->id;

    PurpleConversationType ctype = purple_conversation_get_type(conv);
    std::string cname = std::string(purple_conversation_get_name(conv));

    http.request(url, HTTPFlag::AUTH | HTTPFlag::LARGE,
        [this, path, token, ctype, cname]
        (int status, const guchar *data, gsize len)
        {
            if (status == 200 && data && len > 0) {
                g_file_set_contents(path.c_str(), (const char *)data, len, nullptr);

                temp_files.push_back(path);

                PurpleConversation *conv = purple_find_conversation_with_account(
                    ctype, cname.c_str(), acct);

                if (conv) {
                    Attachment *att = conv_attachment_get(conv, token);
                    if (att)
                        att->path = path;
                }

                purple_notify_uri(conn, path.c_str());
            } else {
                notify_error("Failed to download attachment.");
            }
        });

    return PURPLE_CMD_RET_OK;
}
Exemple #16
0
static void refresh_lcd_file(void) {
	char targetfile[256];
	char tmpfile[256];
	char channame[32];

	if(cfg.lcd_output_path == NULL){
		snprintf(targetfile, sizeof(targetfile),"%s%s", get_tmp_dir(), "/oscam.lcd");
		snprintf(tmpfile, sizeof(tmpfile), "%s%s.tmp", get_tmp_dir(), "/oscam.lcd");
	} else {
		snprintf(targetfile, sizeof(targetfile),"%s%s", cfg.lcd_output_path, "/oscam.lcd");
		snprintf(tmpfile, sizeof(tmpfile), "%s%s.tmp", cfg.lcd_output_path, "/oscam.lcd");
	}

	int8_t iscccam = 0;
	int32_t seconds = 0, secs = 0, fullmins = 0, mins = 0, fullhours = 0, hours = 0,	days = 0;
	time_t now = time((time_t*)0);


	while(running) {
		now = time((time_t*)0);
		int16_t cnt = 0, idx = 0, count_r = 0, count_p = 0, count_u = 0;
		FILE *fpsave;

		if((fpsave = fopen(tmpfile, "w"))){

			idx = 0;
			int16_t i;
			char *type;
			char *label;
			char *status;

			// Statuslines start
			secs = 0; fullmins = 0; mins = 0; fullhours = 0; hours = 0; days = 0;

			seconds = now - first_client->login;
			secs = seconds % 60;
			if (seconds > 60) {
				fullmins = seconds / 60;
				mins = fullmins % 60;
				if(fullmins > 60) {
					fullhours = fullmins / 60;
					hours = fullhours % 24;
					days = fullhours / 24;
				}
			}

			fprintf(fpsave,"Version: %s\n", CS_VERSION);
			fprintf(fpsave,"Revision: %s\n", CS_SVN_VERSION);
			if(days == 0)
				fprintf(fpsave, "up: %02d:%02d:%02d\n", hours, mins, secs);
			else
				fprintf(fpsave, "up: %02dd %02d:%02d:%02d\n", days, hours, mins, secs);
			fprintf(fpsave,"totals: %d/%d/%d/%d/%d/%d\n", first_client->cwfound, first_client->cwnot, first_client->cwignored, first_client->cwtout, first_client->cwcache, first_client->cwtun);
			fprintf(fpsave,"uptime: %d\n", seconds);
			// Statuslines end

			// Readertable head
			fprintf(fpsave,"Typ| Label      | Idle         | w | s | b | e | St\n");
			fprintf(fpsave,"---+------------+--------------+---+---+---+---+----\n");

			struct s_client *cl;

			// Reader/Proxy table start
			for ( i=0, cl=first_client; cl ; cl=cl->next, i++) {

				if ((cl->typ=='r' || cl->typ=='p') && ((now - cl->last) < 20 || !cfg.lcd_hide_idle)){
					type = "";
					label = "";
					status = "OFF";
					secs = 0; fullmins = 0; mins = 0; fullhours = 0; hours = 0; days = 0;

					seconds = now - cl->last;

					if (cl->typ == 'r'){
						type = "R";
						idx = count_r;
						label = cl->reader->label;
						if (cl->reader->card_status == CARD_INSERTED)
							status = "OK";
						count_r++;
					}

					else if (cl->typ == 'p'){
						type = "P";
						iscccam = 0;
						idx = count_p;
						label = cl->reader->label;
						if ((strncmp(monitor_get_proto(cl), "cccam", 5) == 0))
							iscccam = 1;

						if (cl->reader->card_status == CARD_INSERTED)
							status = "CON";

						count_p++;
					}


					secs = seconds % 60;
					if (seconds > 60) {
						fullmins = seconds / 60;
						mins = fullmins % 60;
						if(fullmins > 60) {
							fullhours = fullmins / 60;
							hours = fullhours % 24;
							days = fullhours / 24;
						}
					}

					int16_t written = 0, skipped = 0, blocked = 0, error = 0;

					char *emmtext;
					if(cs_malloc(&emmtext, 16 * sizeof(char), -1)){
						if(cl->typ == 'r' || !iscccam ){
							for (i=0; i<4; i++) {
								error += cl->reader->emmerror[i];
								blocked += cl->reader->emmblocked[i];
								skipped += cl->reader->emmskipped[i];
								written += cl->reader->emmwritten[i];
							}
							snprintf(emmtext, 16, "%3d|%3d|%3d|%3d",
									written > 999? 999 : written,
									skipped > 999? 999 : skipped,
									blocked > 999? 999 : blocked,
									error > 999? 999 : error);

						}
#ifdef MODULE_CCCAM
						else if(cl->typ == 'p' && iscccam ){
							struct cc_data *rcc = cl->cc;
							if(rcc){
								LLIST *cards = rcc->cards;
								if (cards) {
									int32_t cnt = ll_count(cards);
									int32_t locals = rcc->num_hop1;
									snprintf(emmtext, 16, " %3d/%3d card%s", locals, cnt, (cnt > 1)? "s ": "  ");
								}
							} else {
								snprintf(emmtext, 16, "   No cards    ");
							}
						}
#endif
						else {
							snprintf(emmtext, 16, "               ");
						}

					}

					if(days == 0) {
						fprintf(fpsave,"%s%d | %-10.10s |     %02d:%02d:%02d |%s| %s\n",
								type, idx, label, hours, mins,
								secs, emmtext, status);
					} else {
						fprintf(fpsave,"%s%d | %-10.10s |% 3dd %02d:%02d:%02d |%s| %s\n",
								type, idx, label, days, hours, mins,
								secs, emmtext, status);
					}
					free(emmtext);
				}
			}

			fprintf(fpsave,"---+------------+--------------+---+---+---+--++----\n");
			// Reader/Proxy table end


			// Usertable start
			fprintf(fpsave,"Typ| Label      | Channel                     | Time\n");
			fprintf(fpsave,"---+------------+-----------------------------+-----\n");

			/*
			//Testclient
			fprintf(fpsave,"%s%d | %-10.10s | %-10.10s:%-17.17s| % 4d\n",
					"U",
					1,
					"test",
					"Sky De",
					"Discovery Channel",
					568);

			*/

			for ( i=0, cl=first_client; cl ; cl=cl->next, i++) {

				seconds = now - cl->lastecm;

				if (cl->typ == 'c' && seconds < 15){
					type = "U";
					idx = count_u;
					label = cl->account->usr;
					count_u++;

					get_servicename(cl, cl->last_srvid, cl->last_caid, channame);
					fprintf(fpsave,"%s%d | %-10.10s | %-10.10s:%-17.17s| % 4d\n",
							type,
							idx,
							label,
							cl->last_srvidptr && cl->last_srvidptr->prov ? cl->last_srvidptr->prov : "",
									cl->last_srvidptr && cl->last_srvidptr->name ? cl->last_srvidptr->name : "",
											cl->cwlastresptime);

				}
			}
			fprintf(fpsave,"---+------------+-----------------------------+-----\n");
			// Usertable end
			fclose(fpsave);
		}

		idx = 0;
		cs_sleepms(cfg.lcd_write_intervall * 1000);
		cnt++;

		if(rename(tmpfile, targetfile) < 0)
			cs_log("An error occured while writing oscam.lcd file %s.", targetfile);

	}

}
Exemple #17
0
/*******************************
  web_to_disk

return -1 on error
return 0 on success
 ******************************/
int web_to_disk(char * url,char * filename)
{
	CURL * easyhandle;
	char * proxy;
	int err;
	int fd;
	pthread_t thread;
	void * thread_ret;
	struct timespec t;
	char curl_error_buffer[CURL_ERROR_SIZE];
	char * tmp_dir;
	static long count = 0;

	if(backup_dir) {
		sprintf(filename,"%s/%s.%d.%ld",backup_dir,TMP_FILE,(int)pthread_self(),count);
		count++;
	} else {
		tmp_dir = get_tmp_dir();
		sprintf(filename,"%s/%s.%d",tmp_dir,TMP_FILE,(int)pthread_self());
		free(tmp_dir);
	}

	fd = open(filename,O_CREAT| O_TRUNC | O_RDWR, S_IRWXU);
	if( fd == -1 ) {
		printd(DEBUG_ERROR,"Can't open %s\n", filename);
		return -1;
	}

	easyhandle = curl_easy_init();
	if(easyhandle == NULL) {
		close(fd);
		printd(DEBUG_ERROR,"curl_easy_init failed");
		return -1;
	}

	proxy = getenv("http_proxy");
	if(proxy) {
		printd(DEBUG_HTTP,"Set proxy to %s\n",proxy);
		curl_easy_setopt(easyhandle, CURLOPT_PROXY, proxy);
	}
	curl_easy_setopt(easyhandle, CURLOPT_URL, url);
	curl_easy_setopt(easyhandle, CURLOPT_WRITEFUNCTION, data_to_file);
	curl_easy_setopt(easyhandle, CURLOPT_WRITEDATA, (void *)&fd);
	curl_easy_setopt(easyhandle, CURLOPT_TIMEOUT, DEF_HTTP_TIMEOUT);
	curl_easy_setopt(easyhandle, CURLOPT_NOSIGNAL, 1);
	curl_easy_setopt(easyhandle, CURLOPT_ERRORBUFFER, curl_error_buffer);
	curl_easy_setopt(easyhandle, CURLOPT_FOLLOWLOCATION, 1);
	curl_easy_setopt(easyhandle, CURLOPT_USERAGENT, "web-shooter/1.0");

	pthread_create(&thread,NULL,async_perform,easyhandle);

	clock_gettime(CLOCK_REALTIME, &t);
	t.tv_sec += DEF_HTTP_TIMEOUT + 2;
	err = pthread_timedjoin_np(thread,&thread_ret,&t);
	if(err) {
		pthread_cancel(thread);
		printd(DEBUG_ERROR,"pthread_timedjoin_np failed: %s\n",strerror(err));
		curl_easy_cleanup(easyhandle);
		close(fd);
		return -1;
	}
	if(thread_ret != CURLE_OK) {
		printd(DEBUG_ERROR,"curl_easy_perform failed: %s\n",curl_error_buffer);
		curl_easy_cleanup(easyhandle);
		close(fd);
		return -1;
	}

	curl_easy_cleanup(easyhandle);

	close(fd);
	printd(DEBUG_ERROR,"%s ==> %s OK\n",url,filename);

	return 0;
}
Exemple #18
0
int
main(int argc, char *argv[])
{
  int     i = 1, j = 0;
  char   *key = 0;
  path_t  cpp_opts = {0};
  int     code = 0;
  int     prepare_flags = 0;
  unsigned char *user = 0, *group = 0, *workdir = 0;

#if HAVE_SETSID - 0
  path_t  log_path;
#endif /* HAVE_SETSID */

  int pid = -1;
  char **argv_restart = 0;
  unsigned char *ejudge_xml_path = 0;
  unsigned char *compile_cfg_path = 0;
  path_t compile_cfg_buf = { 0 };
  path_t contests_home_dir = { 0 };
  path_t compile_home_dir = { 0 };

#if HAVE_OPEN_MEMSTREAM - 0
  FILE *lang_log_f = 0;
  char *lang_log_t = 0;
  size_t lang_log_z = 0;
#endif /* HAVE_OPEN_MEMSTREAM */

  path_t tmp_path;
  int tmp_len;

#if defined __WIN32__
  path_t tmp_dir = { 0 };
  path_t std_compile_home_dir = { 0 };
#endif

  enum { SUBST_SIZE = 16 };
  const unsigned char *subst_src[SUBST_SIZE];
  const unsigned char *subst_dst[SUBST_SIZE];
  const unsigned char **subst_src_ptr = 0;
  const unsigned char **subst_dst_ptr = 0;

  start_set_self_args(argc, argv);
  XCALLOC(argv_restart, argc + 2);
  argv_restart[j++] = argv[0];

  //if (argc == 1) goto print_usage;
  code = 1;

  while (i < argc) {
    if (!strcmp(argv[i], "-i")) {
      initialize_mode = 1;
      i++;
    } else if (!strcmp(argv[i], "-k")) {
      if (++i >= argc) goto print_usage;
      argv_restart[j++] = argv[i];
      key = argv[i++];
    } else if (!strcmp(argv[i], "-D")) {
      daemon_mode = 1;
      i++;
    } else if (!strcmp(argv[i], "-R")) {
      restart_mode = 1;
      i++;
    } else if (!strncmp(argv[i], "-D", 2)) {
      if (cpp_opts[0]) pathcat(cpp_opts, " ");
      argv_restart[j++] = argv[i];
      pathcat(cpp_opts, argv[i++]);
    } else if (!strcmp(argv[i], "-u")) {
      if (++i >= argc) goto print_usage;
      user = argv[i++];
    } else if (!strcmp(argv[i], "-g")) {
      if (++i >= argc) goto print_usage;
      group = argv[i++];
    } else if (!strcmp(argv[i], "-C")) {
      if (++i >= argc) goto print_usage;
      workdir = argv[i++];
    } else if (!strcmp(argv[i], "-d")) {
      daemon_mode = 1;
      i++;
    } else if (!strcmp(argv[i], "-r")) {
      if (++i >= argc) goto print_usage;
      snprintf(contests_home_dir, sizeof(contests_home_dir), "%s", argv[i++]);
    } else if (!strcmp(argv[i], "-c")) {
      if (++i >= argc) goto print_usage;
      snprintf(compile_home_dir, sizeof(compile_home_dir), "%s", argv[i++]);
    } else if (!strcmp(argv[i], "-x")) {
      if (++i >= argc) goto print_usage;
      ejudge_xml_path = argv[i++];
      argv_restart[j++] = "-x";
      argv_restart[j++] = ejudge_xml_path;
    } else if (!strcmp(argv[i], "--help")) {
      code = 0;
      goto print_usage;
    } else break;
  }
  argv_restart[j++] = "-R";
  if (i < argc) {
    compile_cfg_path = argv[i];
    argv_restart[j++] = argv[i++];
  }
  if (i < argc) goto print_usage;
  argv_restart[j] = 0;
  start_set_args(argv_restart);

  if ((pid = start_find_process("ej-compile", 0)) > 0) {
    fprintf(stderr, "%s: is already running as pid %d\n", argv[0], pid);
    return 1;
  }

#if defined EJUDGE_XML_PATH
  if (!ejudge_xml_path) ejudge_xml_path = EJUDGE_XML_PATH;
#endif /* EJUDGE_XML_PATH */
  if (!ejudge_xml_path) {
    fprintf(stderr, "%s: ejudge.xml configuration file is not specified\n",
            argv[0]);
    return 1;
  }
#if defined EJUDGE_CONTESTS_HOME_DIR
  if (contests_home_dir[0]) {
    tmp_len = strlen(EJUDGE_CONTESTS_HOME_DIR);
    if (!strncmp(ejudge_xml_path, EJUDGE_CONTESTS_HOME_DIR, tmp_len)) {
      snprintf(tmp_path, sizeof(tmp_path), "%s%s",
               contests_home_dir, ejudge_xml_path + tmp_len);
      ejudge_xml_path = xstrdup(tmp_path);
    }
  }
#endif

#ifndef __WIN32__
  ejudge_config = ejudge_cfg_parse(ejudge_xml_path);
  if (!ejudge_config) {
    fprintf(stderr, "%s: ejudge.xml is invalid\n", argv[0]);
    return 1;
  }
#endif

#ifdef __WIN32__
  if (!compile_home_dir[0] && contests_home_dir[0]) {
    snprintf(compile_home_dir, sizeof(compile_home_dir),
             "%s/win32_compile", contests_home_dir);
  }

  if (!compile_cfg_path && compile_home_dir[0]) {
    snprintf(compile_cfg_buf, sizeof(compile_cfg_buf),
             "%s/conf/compile.cfg", compile_home_dir);
    compile_cfg_path = xstrdup(compile_cfg_buf);
  }
  if (!compile_cfg_path && contests_home_dir[0]) {
    snprintf(compile_cfg_buf, sizeof(compile_cfg_buf),
             "%s/win32_compile/conf/compile.cfg",
             contests_home_dir);
    compile_cfg_path = xstrdup(compile_cfg_buf);
  }

  if (!compile_cfg_path && ejudge_config && ejudge_config->compile_home_dir) {
    snprintf(compile_cfg_buf, sizeof(compile_cfg_buf),
             "%s/conf/compile.cfg", ejudge_config->compile_home_dir);
    compile_cfg_path = compile_cfg_buf;
  }
  if (!compile_cfg_path && ejudge_config && ejudge_config->contests_home_dir) {
    snprintf(compile_cfg_buf, sizeof(compile_cfg_buf),
             "%s/win32_compile/conf/compile.cfg",
             ejudge_config->contests_home_dir);
    compile_cfg_path = compile_cfg_buf;
  }
#if defined EJUDGE_CONTESTS_HOME_DIR
  if (!compile_cfg_path) {
    snprintf(compile_cfg_buf, sizeof(compile_cfg_buf),
             "%s/compile/conf/win32_compile.cfg", EJUDGE_CONTESTS_HOME_DIR);
    compile_cfg_path = compile_cfg_buf;
  }
#endif /* EJUDGE_CONTESTS_HOME_DIR */
  if (!compile_cfg_path) {
    fprintf(stderr, "%s: compile.cfg is not specified\n", argv[0]);
    return 1;
  }
#else
  if (!compile_cfg_path && ejudge_config && ejudge_config->compile_home_dir) {
    snprintf(compile_cfg_buf, sizeof(compile_cfg_buf),
             "%s/conf/compile.cfg", ejudge_config->compile_home_dir);
    compile_cfg_path = compile_cfg_buf;
  }
  if (!compile_cfg_path && ejudge_config && ejudge_config->contests_home_dir) {
    snprintf(compile_cfg_buf, sizeof(compile_cfg_buf),
             "%s/compile/conf/compile.cfg", ejudge_config->contests_home_dir);
    compile_cfg_path = compile_cfg_buf;
  }
#if defined EJUDGE_CONTESTS_HOME_DIR
  if (!compile_cfg_path) {
    snprintf(compile_cfg_buf, sizeof(compile_cfg_buf),
             "%s/compile/conf/compile.cfg", EJUDGE_CONTESTS_HOME_DIR);
    compile_cfg_path = compile_cfg_buf;
  }
#endif /* EJUDGE_CONTESTS_HOME_DIR */
  if (!compile_cfg_path) {
    fprintf(stderr, "%s: compile.cfg is not specified\n", argv[0]);
    return 1;
  }
#endif /* __WIN32__ */

  if (start_prepare(user, group, workdir) < 0) return 1;

  memset(subst_src, 0, sizeof(subst_src));
  memset(subst_dst, 0, sizeof(subst_dst));

#ifdef __WIN32__
  int subst_idx = 0;
  if (compile_home_dir[0]) {
    if (ejudge_config) {
      subst_src[subst_idx] = ejudge_config->compile_home_dir;
      subst_dst[subst_idx] = compile_home_dir;
      subst_idx++;
    } else {
      snprintf(std_compile_home_dir, sizeof(std_compile_home_dir),
               "%s/compile", EJUDGE_CONTESTS_HOME_DIR);
      subst_src[subst_idx] = std_compile_home_dir;
      subst_dst[subst_idx] = compile_home_dir;

      subst_idx++;
    }
  }
  if (contests_home_dir[0]) {
    subst_src[subst_idx] = EJUDGE_CONTESTS_HOME_DIR;
    subst_dst[subst_idx] = contests_home_dir;
    subst_idx++;
  }
  if (compile_home_dir[0]) {
    subst_src[subst_idx] = "/COMPILE_HOME_DIR";
    subst_dst[subst_idx] = compile_home_dir;
    subst_idx++;
  }
  if (contests_home_dir[0]) {
    subst_src[subst_idx] = "/CONTESTS_HOME_DIR";
    subst_dst[subst_idx] = contests_home_dir;
    subst_idx++;
  }

  subst_src[subst_idx] = "/TMPDIR";
  subst_dst[subst_idx] = get_tmp_dir(tmp_dir, sizeof(tmp_dir));
  subst_idx++;

  fprintf(stderr, "Win32 substitutions:\n");
  for (int j = 0; subst_src[j]; ++j) {
    fprintf(stderr, "%s -> %s\n", subst_src[j], subst_dst[j]);
  }
  subst_src_ptr = subst_src;
  subst_dst_ptr = subst_dst;
#endif

  if (prepare(&serve_state, compile_cfg_path, prepare_flags, PREPARE_COMPILE,
              cpp_opts, 0, subst_src_ptr, subst_dst_ptr) < 0)
    return 1;
#if HAVE_OPEN_MEMSTREAM - 0
  if (!(lang_log_f = open_memstream(&lang_log_t, &lang_log_z))) return 1;
  if (lang_config_configure(lang_log_f, serve_state.global->lang_config_dir,
                            serve_state.max_lang, serve_state.langs) < 0) {
    fclose(lang_log_f); lang_log_f = 0;
    fprintf(stderr, "%s", lang_log_t);
    return 1;
  }
  close_memstream(lang_log_f); lang_log_f = 0;
#else
  if (lang_config_configure(stderr, serve_state.global->lang_config_dir,
                            serve_state.max_lang, serve_state.langs) < 0)
    return 1;
#endif /* HAVE_OPEN_MEMSTREAM */
  if (key && filter_languages(key) < 0) return 1;
  if (create_dirs(&serve_state, PREPARE_COMPILE) < 0) return 1;
  if (check_config() < 0) return 1;
  if (initialize_mode) return 0;

#if HAVE_SETSID - 0
  log_path[0] = 0;
#if defined EJUDGE_CONTESTS_HOME_DIR
  if (!log_path[0]) {
    snprintf(log_path, sizeof(log_path), "%s/var/ej-compile.log", EJUDGE_CONTESTS_HOME_DIR);
  }
#endif
  if (!log_path[0]) {
    snprintf(log_path, sizeof(log_path), "%s/ej-compile.log", serve_state.global->var_dir);
  }

  if (daemon_mode) {
    // daemonize itself
    if (start_open_log(log_path) < 0)
      return 1;

    if ((pid = fork()) < 0) return 1;
    if (pid > 0) _exit(0);
    if (setsid() < 0) return 1;

#if HAVE_OPEN_MEMSTREAM - 0 == 1
    fprintf(stderr, "%s", lang_log_t);
#endif /* HAVE_OPEN_MEMSTREAM */
  } else if (restart_mode) {
    if (start_open_log(log_path) < 0)
      return 1;
  }
#endif /* HAVE_SETSID */

#if HAVE_OPEN_MEMSTREAM - 0 == 1
  xfree(lang_log_t); lang_log_t = 0; lang_log_z = 0;
#endif /* HAVE_OPEN_MEMSTREAM */

  if (do_loop() < 0) return 1;

  if (interrupt_restart_requested()) start_restart();

  return 0;

 print_usage:
  printf("Usage: %s [ OPTS ] [config-file]\n", argv[0]);
  printf("  -k key - specify language key\n");
  printf("  -DDEF  - define a symbol for preprocessor\n");
  printf("  -D     - start in daemon mode\n");
  printf("  -i     - initialize mode: create all dirs and exit\n");
  printf("  -k KEY - specify a language filter key\n");
  printf("  -u U   - start as user U (only as root)\n");
  printf("  -g G   - start as group G (only as root)\n");
  printf("  -C D   - change directory to D\n");
  printf("  -x X   - specify a path to ejudge.xml file\n");
  printf("  -r S   - substitute ${CONTESTS_HOME_DIR} for S in the config\n");
  printf("  -c C   - substitute ${COMPILE_HOME_DIR} for C in the config\n");
  return code;
}
Exemple #19
0
int vzm_connect(const char *password, char *const *argv,
	int *ssh_in, int *ssh_out, pid_t *ssh_pid)
{
	int in[2], out[2];
	pid_t pid;
	long flags;
	int status, retcode;
	size_t size;

	if ((pipe(in) < 0) || (pipe(out) < 0))
		return vzm_error(VZM_ERR_SYSTEM, "pipe() error, %m");

	flags = fcntl(out[0], F_GETFL, &flags);
	flags = flags | O_NONBLOCK;
	fcntl(out[0], F_SETFL, flags);

	pid = fork();
	if (pid < 0) {
		close(in[1]); close(out[0]);
		close(in[0]); close(out[1]);
		return vzm_error(VZM_ERR_SYSTEM, "fork() : %m");
	} else if (pid == 0) {
		int fd;
		/* allow C-c for child */
		signal(SIGINT, SIG_DFL);
		/* redirect stdout to out and stdin to in */
		close(STDIN_FILENO); close(STDOUT_FILENO);
		close(in[1]); close(out[0]);
		dup2(in[0], STDIN_FILENO);
		dup2(out[1], STDOUT_FILENO);
		if ((fd = open("/dev/null", O_WRONLY)) != -1) {
			close(STDERR_FILENO);
			dup2(fd, STDERR_FILENO);
		}
		close(in[0]); close(out[1]);
		setsid();
		if (password) {
			/* if password is needs, create askpass file */
			int fd;
			FILE *fp;
			char tmpdir[PATH_MAX+1];
			char path[PATH_MAX+1];

			/* get temporary directory */
			if (get_tmp_dir(tmpdir, sizeof(tmpdir)))
				tmpdir[0] = '\0';

			snprintf(path, sizeof(path), "%s/askpass.XXXXXX", tmpdir);
			if ((fd = mkstemp(path)) == -1)
				return vzm_error(VZM_ERR_SYSTEM, "mkstemp(%s) : %m", path);

			if ((fp = fdopen(fd, "w")) == NULL) {
				close(fd);
				unlink(path);
				return vzm_error(VZM_ERR_SYSTEM, "fdopen(%s) : %m", path);
			}
			fprintf(fp, "#!/bin/sh\necho \"%s\"\nrm -f \"%s\"\n",
				password, path);
			fclose(fp);
			chmod(path, S_IRUSR|S_IXUSR);
			setenv("DISPLAY", "dummy", 0);
			setenv("SSH_ASKPASS", path, 1);
		}
		execvp(argv[0], argv);
		exit(VZM_ERR_SYSTEM);
	}
	close(in[0]); close(out[1]);

	while ((pid = waitpid(pid, &status, WNOHANG)) == -1)
		if (errno != EINTR)
			break;

	if (pid < 0) {
		close(in[1]); close(out[0]);
		return vzm_error(VZM_ERR_SYSTEM, "waitpid() error: %m");
	}
	if (WIFEXITED(status)) {
		if ((retcode = WEXITSTATUS(status))) {
			return vzm_error(VZM_ERR_SYSTEM,
				"%s failed, exitcode=%d", argv[0], retcode);
		}
	} else if (WIFSIGNALED(status)) {
		return vzm_error(VZM_ERR_SYSTEM, "%s got signal %d",
			argv[0], WTERMSIG(status));
	} else {
		return vzm_error(VZM_ERR_SYSTEM, "%s exited with status %d",
				argv[0], status);
	}

	*ssh_in = in[1];
	*ssh_out = out[0];
	*ssh_pid = pid;
	return 0;
}
Exemple #20
0
int mpkgSys::nativize_directory(string input_dir) {
	output_dir = get_tmp_dir();
	ftw(input_dir.c_str(), _nativize_dir, 100);
	return 0;
}