int main(int argc, const char * const * argv, const char * const *env) { apr_app_initialize(&argc, &argv, &env); apr_terminate(); }
int main(int argc, char **argv, char **env) { if (apr_app_initialize(&argc, (const char * const **) argv, (const char * const **) env) != APR_SUCCESS) { printf("apr_app_initialize failed\n"); return -1; } apr_pool_t *pool = NULL; apr_pool_create(&pool, NULL); request_rec *r = test_setup(pool); OpenSSL_add_all_digests(); char *result = all_tests(pool, r); if (result != 0) { printf("Failed: %s\n", result); } else { printf("All %d tests passed!\n", test_nr_run); } EVP_cleanup(); apr_pool_destroy(pool); apr_terminate(); return result != 0; }
int main( int argc, char const * const *argv ) { json_t *json; int ret; apr_status_t status; apr_pool_t *mp; apr_file_t *xml_fp; apr_file_t *out_fp; const char *xml_file; const char *out_file; int preserve_root; int indent; apr_app_initialize( NULL, NULL, NULL ); apr_pool_create( &mp, NULL ); xml2json_init( argc, argv, mp, &xml_file, &out_file, &preserve_root, &indent ); if ( open_apr_input_file( mp, xml_file, &xml_fp ) && open_apr_output_file( mp, out_file, &out_fp ) && xml_to_json( mp, xml_fp, !preserve_root, &json ) ) { json_dump( out_fp, json, indent ); ret = 0; } else { fprintf( stderr, "failed to convert\n" ); ret = 1; } apr_pool_destroy( mp ); apr_terminate(); return ret; }
int main(int argc, char const * const argv[], char const * const envp[]) { apr_status_t status(apr_app_initialize(&argc, &argv, &envp)); if (status != APR_SUCCESS) { fprintf(stderr, "apr_app_initialize() != APR_SUCCESS\n"); return 1; } else try { return Main(argc, argv, envp); } catch (const CYException &error) { CYPool pool; fprintf(stderr, "%s\n", error.PoolCString(pool)); return 1; } }
int main (int argc, char *argv[]) { unsigned int number_failed; apr_app_initialize(&argc, (const char * const **) &argv, NULL); Suite *s = mod_auth_cas_suite(); SRunner *sr = srunner_create(s); srunner_run_all(sr, CK_NORMAL); number_failed = srunner_ntests_failed(sr); srunner_free(sr); apr_terminate(); return (number_failed != 0); }
int main (int argc, const char * const argv[], const char * const env[]) { apr_app_initialize (&argc, &argv, &env); apr_pool_create (&global_pool, NULL); FiberManager *manager = fiber_manager_new (); for (uintptr_t j = 0; j < 1024; j++) fiber_manager_spawn (manager, 16384, callback, (void *) j); fiber_manager_run (manager); fiber_manager_free (manager); apr_pool_destroy (global_pool); return 0; }
int main(int argc, const char * const *argv) { apr_pool_t *pool; UploaderConfig *config; int status; apr_app_initialize(&argc, &argv, NULL); apr_pool_create(&pool, NULL); config = NULL; status = 0; try { config = UploaderConfigReader::read(pool, CONF_FILE_NAME); config->child_init(); // ベンチマーク用 bench_count = atoi(getenv("UPLOADER_BENCH")); if (bench_count == 0) { bench_count++; } STRACE_MARKER(); for (apr_size_t i = 0; i < bench_count; i++) { TemporaryPool temp_pool(pool); CGIResponse::Handle handle(temp_pool.get()); status = uploader_command_handler<CGIResponse> (&handle, config, arg); } STRACE_MARKER(); config->finalize(); apr_pool_destroy(pool); apr_terminate(); return status; } catch(const char *message) { std::cout << "Fatal Error: " << message << std::endl; if (config != NULL) { config->finalize(); } apr_pool_destroy(pool); apr_terminate(); return EXIT_FAILURE; } }
/* Compile with * $> export APR_LIBS="`apr-1-config --cflags --cppflags --includes --ldflags --link-ld --libs`" * $> export APU_LIBS="`apu-1-config --includes --ldflags --link-ld --libs`" * $> gcc aprHashtable.c -o aprHashtable $APR_LIBS $APU_LIBS */ int main(int argc, const char* const* argv) { apr_status_t rv; apr_pool_t *p = NULL; struct userRecord *cUser = NULL; struct userRecord *readUser = NULL; int i = 0; char countName[12]; apr_hash_index_t *hidx = NULL; apr_app_initialize(&argc, &argv, NULL); atexit(apr_terminate); apr_pool_create(&p, NULL); apr_hash_t *ht = apr_hash_make(p); apr_cpystrn(countName, "Jens Frey ", 12); for (i=0; i < 26; i++) { countName[10] = (char) i + 65; cUser = apr_palloc(p, sizeof(struct userRecord)); apr_cpystrn(cUser->username, countName, strlen(countName) + 1); apr_cpystrn(cUser->password, "secret", strlen("secret") + 1); cUser->creationDate = apr_time_now(); apr_hash_set(ht, cUser->username, APR_HASH_KEY_STRING, cUser); print(cUser); } for (hidx = apr_hash_first(p, ht); hidx; hidx = apr_hash_next(hidx)) { apr_hash_this(hidx, NULL, NULL, (void*) &readUser); print(readUser); } readUser = apr_hash_get(ht, "Jens Frey G", APR_HASH_KEY_STRING); printf("\n\n"); print(readUser); printf("Hashtable size: %d bytes\n", apr_hash_count(ht) * sizeof(struct userRecord) + apr_hash_count(ht) * sizeof(readUser->username)); apr_terminate(); return rv; }
static process_rec *init_process(int *argc, const char * const * *argv) { process_rec *process; apr_pool_t *cntx; apr_status_t stat; const char *failed = "apr_app_initialize()"; stat = apr_app_initialize(argc, argv, NULL); if (stat == APR_SUCCESS) { failed = "apr_pool_create()"; stat = apr_pool_create(&cntx, NULL); } if (stat != APR_SUCCESS) { /* For all intents and purposes, this is impossibly unlikely, * but APR doesn't exist yet, we can't use it for reporting * these earliest two failures; */ char ctimebuff[APR_CTIME_LEN]; apr_ctime(ctimebuff, apr_time_now()); fprintf(stderr, "[%s] [crit] (%d) %s: %s failed " "to initial context, exiting\n", ctimebuff, stat, (*argv)[0], failed); apr_terminate(); exit(1); } apr_pool_tag(cntx, "process"); ap_open_stderr_log(cntx); /* Now we have initialized apr and our logger, no more * exceptional error reporting required for the lifetime * of this server process. */ process = apr_palloc(cntx, sizeof(process_rec)); process->pool = cntx; apr_pool_create(&process->pconf, process->pool); apr_pool_tag(process->pconf, "pconf"); process->argc = *argc; process->argv = *argv; process->short_name = apr_filepath_name_get((*argv)[0]); return process; }
void NuPIC::init() { if (isInitialized()) return; // internal consistency check. Nonzero should be impossible. NTA_CHECK(networks_.size() == 0) << "Internal error in NuPIC::init()"; // Initialize APR int argc=1; const char *argv[1] = {"NuPIC"}; // TODO: move to OS::initialize()? int result = apr_app_initialize(&argc, (const char* const **)&argv, 0 /*env*/); if (result) NTA_THROW << "Error initializing APR (code " << result << ")"; initialized_ = true; }
int main(int argc, const char* const argv[]) { apr_pool_t* pool = NULL; apr_status_t status = APR_SUCCESS; #ifdef WIN32 #ifndef _DEBUG // only Release configuration dump generating SetUnhandledExceptionFilter(dbg_top_level_filter); #endif #endif setlocale(LC_ALL, ".ACP"); setlocale(LC_NUMERIC, "C"); #ifdef USE_GETTEXT bindtextdomain("hc", LOCALEDIR); /* set the text message domain */ textdomain("hc"); #endif /* USE_GETTEXT */ status = apr_app_initialize(&argc, &argv, NULL); if(status != APR_SUCCESS) { lib_printf(_("Couldn't initialize APR")); lib_new_line(); out_print_error(status); return EXIT_FAILURE; } atexit(apr_terminate); apr_pool_create(&pool, NULL); hsh_initialize_hashes(pool); configuration_ctx_t* configuration_ctx = apr_pcalloc(pool, sizeof(configuration_ctx_t)); configuration_ctx->pool = pool; configuration_ctx->argc = argc; configuration_ctx->argv = argv; configuration_ctx->pfn_on_string = &prhc_on_string; configuration_ctx->pfn_on_hash = &prhc_on_hash; configuration_ctx->pfn_on_file = &prhc_on_file; configuration_ctx->pfn_on_dir = &prhc_on_dir; conf_run_app(configuration_ctx); apr_pool_destroy(pool); return EXIT_SUCCESS; }
int main(int argc, char const * const * argv, char const * const * env) { apr_app_initialize(&argc, &argv, &env); atexit(apr_terminate); umask(0002); if (argc != 4) { std::cerr << "Usage: " << argv[0] << " <Store Path> <Rapid Tag> <Output>\n"; return 1; } try { makeZip(argv[1], argv[2], argv[3]); } catch (std::exception const & Exception) { std::cerr << Exception.what() << "\n"; return 1; } }
/* * main */ int main(int argc, const char * const argv[]) { apr_off_t max; apr_time_t current, repeat, delay, previous; apr_status_t status; apr_pool_t *pool, *instance; apr_getopt_t *o; apr_finfo_t info; int retries, isdaemon, limit_found, intelligent, dowork; char opt; const char *arg; char *proxypath, *path; interrupted = 0; repeat = 0; isdaemon = 0; dryrun = 0; limit_found = 0; max = 0; verbose = 0; realclean = 0; benice = 0; deldirs = 0; intelligent = 0; previous = 0; /* avoid compiler warning */ proxypath = NULL; if (apr_app_initialize(&argc, &argv, NULL) != APR_SUCCESS) { return 1; } atexit(apr_terminate); if (argc) { shortname = apr_filepath_name_get(argv[0]); } if (apr_pool_create(&pool, NULL) != APR_SUCCESS) { return 1; } apr_pool_abort_set(oom, pool); apr_file_open_stderr(&errfile, pool); apr_signal(SIGINT, setterm); apr_signal(SIGTERM, setterm); apr_getopt_init(&o, pool, argc, argv); while (1) { status = apr_getopt(o, "iDnvrtd:l:L:p:", &opt, &arg); if (status == APR_EOF) { break; } else if (status != APR_SUCCESS) { usage(); } else { switch (opt) { case 'i': if (intelligent) { usage(); } intelligent = 1; break; case 'D': if (dryrun) { usage(); } dryrun = 1; break; case 'n': if (benice) { usage(); } benice = 1; break; case 't': if (deldirs) { usage(); } deldirs = 1; break; case 'v': if (verbose) { usage(); } verbose = 1; break; case 'r': if (realclean) { usage(); } realclean = 1; deldirs = 1; break; case 'd': if (isdaemon) { usage(); } isdaemon = 1; repeat = apr_atoi64(arg); repeat *= SECS_PER_MIN; repeat *= APR_USEC_PER_SEC; break; case 'l': if (limit_found) { usage(); } limit_found = 1; do { apr_status_t rv; char *end; rv = apr_strtoff(&max, arg, &end, 10); if (rv == APR_SUCCESS) { if ((*end == 'K' || *end == 'k') && !end[1]) { max *= KBYTE; } else if ((*end == 'M' || *end == 'm') && !end[1]) { max *= MBYTE; } else if ((*end == 'G' || *end == 'g') && !end[1]) { max *= GBYTE; } else if (*end && /* neither empty nor [Bb] */ ((*end != 'B' && *end != 'b') || end[1])) { rv = APR_EGENERAL; } } if (rv != APR_SUCCESS) { apr_file_printf(errfile, "Invalid limit: %s" APR_EOL_STR APR_EOL_STR, arg); usage(); } } while(0); break; case 'p': if (proxypath) { usage(); } proxypath = apr_pstrdup(pool, arg); if (apr_filepath_set(proxypath, pool) != APR_SUCCESS) { usage(); } break; } /* switch */ } /* else */ } /* while */ if (o->ind != argc) { usage(); } if (isdaemon && (repeat <= 0 || verbose || realclean || dryrun)) { usage(); } if (!isdaemon && intelligent) { usage(); } if (!proxypath || max <= 0) { usage(); } if (apr_filepath_get(&path, 0, pool) != APR_SUCCESS) { usage(); } baselen = strlen(path); #ifndef DEBUG if (isdaemon) { apr_file_close(errfile); apr_proc_detach(APR_PROC_DETACH_DAEMONIZE); } #endif do { apr_pool_create(&instance, pool); now = apr_time_now(); APR_RING_INIT(&root, _entry, link); delcount = 0; unsolicited = 0; dowork = 0; switch (intelligent) { case 0: dowork = 1; break; case 1: retries = STAT_ATTEMPTS; status = APR_SUCCESS; do { if (status != APR_SUCCESS) { apr_sleep(STAT_DELAY); } status = apr_stat(&info, path, APR_FINFO_MTIME, instance); } while (status != APR_SUCCESS && !interrupted && --retries); if (status == APR_SUCCESS) { previous = info.mtime; intelligent = 2; } dowork = 1; break; case 2: retries = STAT_ATTEMPTS; status = APR_SUCCESS; do { if (status != APR_SUCCESS) { apr_sleep(STAT_DELAY); } status = apr_stat(&info, path, APR_FINFO_MTIME, instance); } while (status != APR_SUCCESS && !interrupted && --retries); if (status == APR_SUCCESS) { if (previous != info.mtime) { dowork = 1; } previous = info.mtime; break; } intelligent = 1; dowork = 1; break; } if (dowork && !interrupted) { if (!process_dir(path, instance) && !interrupted) { purge(path, instance, max); } else if (!isdaemon && !interrupted) { apr_file_printf(errfile, "An error occurred, cache cleaning " "aborted." APR_EOL_STR); return 1; } if (intelligent && !interrupted) { retries = STAT_ATTEMPTS; status = APR_SUCCESS; do { if (status != APR_SUCCESS) { apr_sleep(STAT_DELAY); } status = apr_stat(&info, path, APR_FINFO_MTIME, instance); } while (status != APR_SUCCESS && !interrupted && --retries); if (status == APR_SUCCESS) { previous = info.mtime; intelligent = 2; } else { intelligent = 1; } } } apr_pool_destroy(instance); current = apr_time_now(); if (current < now) { delay = repeat; } else if (current - now >= repeat) { delay = repeat; } else { delay = now + repeat - current; } /* we can't sleep the whole delay time here apiece as this is racy * with respect to interrupt delivery - think about what happens * if we have tested for an interrupt, then get scheduled * before the apr_sleep() call and while waiting for the cpu * we do get an interrupt */ if (isdaemon) { while (delay && !interrupted) { if (delay > APR_USEC_PER_SEC) { apr_sleep(APR_USEC_PER_SEC); delay -= APR_USEC_PER_SEC; } else { apr_sleep(delay); delay = 0; } } } } while (isdaemon && !interrupted); if (!isdaemon && interrupted) { apr_file_printf(errfile, "Cache cleaning aborted due to user " "request." APR_EOL_STR); return 1; } return 0; }
int main(int argc, const char *const *argv, const char *const *env) { const char *db_filename = "last_message.db"; int dying = 0; sqlite3 *sql = NULL; lmSQL lmdb = {}; apr_socket_t *acc = NULL; apr_pollset_t *pollset = NULL; APR_DO_OR_DIE(apr_app_initialize(&argc, &argv, &env)); atexit(&apr_terminate); apr_pool_t *pool; APR_DO_OR_DIE(apr_pool_create(&pool, NULL)); if (argc > 2) { return print_usage(); } if (argc == 2) { if (strcmp(argv[1], "--help") == 0) { return print_usage(); } db_filename = argv[1]; } int err; if ((err = sqlite3_open(db_filename, &sql)) != SQLITE_OK) { fprintf(stderr, "Can't open DB (%s): %s.\n", db_filename, sqlite3_errstr(err)); return 1; } int rc; char *rc_msg; const char *CREATE_MESSAGE_TABLES = "CREATE TABLE IF NOT EXISTS messages (" " msgid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," " name BLOB NOT NULL," " left INTEGER NOT NULL," " message BLOB NOT NULL" ");"; rc = sqlite3_exec(sql, CREATE_MESSAGE_TABLES, NULL, NULL, &rc_msg); if (rc != SQLITE_OK) { FAIL("Can't create 'messages' table: %s.\n", rc_msg); sqlite3_close(sql); return 1; } const char *CREATE_MESSAGE_SEEN = "CREATE TABLE IF NOT EXISTS seen (" " name BLOB PRIMARY KEY NOT NULL," " msgid INTEGER NOT NULL" ");"; rc = sqlite3_exec(sql, CREATE_MESSAGE_SEEN, NULL, NULL, &rc_msg); if (rc != SQLITE_OK) { FAIL("Can't create 'seen' table: %s.\n", rc_msg); sqlite3_close(sql); return 1; } lmdb.sql = sql; #define LM_SQLITE_PREP(thing, statement) \ do { \ int prep = \ sqlite3_prepare_v2(sql, (statement), -1, (thing), NULL); \ if (prep != SQLITE_OK) { \ FAIL("SQL compilation error: (%s) while compiling " \ "(%s).\n", \ sqlite3_errmsg(sql), statement); \ goto die; \ } \ } while (0) LM_SQLITE_PREP(&lmdb.put, "INSERT INTO messages (name, left, message) " "VALUES (?, ?, ?);"); LM_SQLITE_PREP(&lmdb.get, "SELECT msgid, left, message " "FROM messages " "WHERE name = ? " "ORDER BY msgid ASC;"); LM_SQLITE_PREP(&lmdb.seen_add, "INSERT INTO seen (name, msgid) " "VALUES (?, ?);"); LM_SQLITE_PREP(&lmdb.seen_del, "DELETE FROM seen " "WHERE name = ?;"); LM_SQLITE_PREP(&lmdb.seen_get, "SELECT msgid FROM seen " "WHERE name = ?;"); LM_SQLITE_PREP(&lmdb.drop, "DELETE FROM messages " "WHERE msgid <= ? " " AND name = ?;"); APR_DO_OR_DIE(apr_socket_create(&acc, APR_INET, SOCK_STREAM, 0, pool)); APR_DO_OR_DIE(apr_socket_opt_set(acc, APR_SO_REUSEADDR, 1)); apr_sockaddr_t *l_addr; APR_DO_OR_DIE( apr_sockaddr_info_get(&l_addr, NULL, APR_INET, 1066, 0, pool)); APR_DO_OR_DIE(apr_socket_bind(acc, l_addr)); APR_DO_OR_DIE(apr_socket_listen(acc, 8)); apr_pollfd_t apr_accept_desc; memset(&apr_accept_desc, 0, sizeof apr_accept_desc); apr_accept_desc.p = pool; apr_accept_desc.desc_type = APR_POLL_SOCKET; apr_accept_desc.desc.s = acc; apr_accept_desc.reqevents = APR_POLLIN; apr_accept_desc.client_data = NULL; APR_DO_OR_DIE(apr_pollset_create(&pollset, 256, pool, 0)); APR_DO_OR_DIE(apr_pollset_add(pollset, &apr_accept_desc)); apr_signal(SIGTERM, shutdown_on_signal); apr_signal(SIGINT, shutdown_on_signal); apr_int32_t signalled_len = 0; const apr_pollfd_t *signalled = NULL; apr_status_t poll_err = 0; for (;;) { if (global_shutting_down) { goto goodnight; } if (!APR_STATUS_IS_EINTR(poll_err)) { APR_DO_OR_DIE(poll_err); } for (apr_int32_t i = 0; i < signalled_len; i++) { const apr_pollfd_t *s = signalled + i; if (s->desc.s == acc) { DEBUG("accept\n"); do_client_accept(acc, pollset, pool, &lmdb); } else { do_client_state_machine(s, pollset); } } poll_err = apr_pollset_poll(pollset, -1, &signalled_len, &signalled); } if (0) { goodnight: fprintf(stderr, "Goodnight!\n"); } if (0) { die: dying = 1; } sqlite3_finalize(lmdb.put); lmdb.put = 0; sqlite3_finalize(lmdb.get); lmdb.get = 0; sqlite3_finalize(lmdb.seen_add); lmdb.seen_add = 0; sqlite3_finalize(lmdb.seen_del); lmdb.seen_del = 0; sqlite3_finalize(lmdb.seen_get); lmdb.seen_get = 0; sqlite3_finalize(lmdb.drop); lmdb.drop = 0; if (sqlite3_close(sql) != SQLITE_OK) { fprintf(stderr, "Error closing DB (%s): %s.\n", db_filename, sqlite3_errmsg(sql)); return 1; } apr_pollset_destroy(pollset); apr_socket_close(acc); return dying; }
int main(int argc, const char * const argv[]) { apr_file_t *infd, *skwrapper; apr_sockaddr_t *skaddr; apr_getopt_t *gopt; apr_socket_t *skt; apr_pool_t *pool; apr_status_t rv; apr_proc_t proc; /* Command line arguments */ int num_to_start = 1, port = 0; const char *interface = NULL; const char *command = NULL; apr_app_initialize(&argc, &argv, NULL); atexit(apr_terminate); apr_pool_create(&pool, NULL); rv = apr_getopt_init(&gopt, pool, argc, argv); if (rv) { return EXIT_FAILURE; } for (;;) { const char *arg; char opt; rv = apr_getopt(gopt, "c:p:i:N:", &opt, &arg); if (APR_STATUS_IS_EOF(rv)) { break; } else if (rv) { usage(); } else { switch (opt) { case 'c': command = arg; break; case 'p': port = atoi(arg); if (! port) { usage(); } break; case 'i': interface = arg; break; case 'N': num_to_start = atoi(arg); if (! num_to_start) { usage(); } break; default: break; } } } if (! command || ! port) { usage(); } rv = apr_sockaddr_info_get(&skaddr, interface, APR_UNSPEC, port, 0, pool); if (rv) { exit_error(rv, "apr_sockaddr_info_get"); } rv = apr_socket_create(&skt, skaddr->family, SOCK_STREAM, APR_PROTO_TCP, pool); if (rv) { exit_error(rv, "apr_socket_create"); } rv = apr_socket_bind(skt, skaddr); if (rv) { exit_error(rv, "apr_socket_bind"); } rv = apr_socket_listen(skt, 1024); if (rv) { exit_error(rv, "apr_socket_listen"); } rv = apr_proc_detach(APR_PROC_DETACH_DAEMONIZE); if (rv) { exit_error(rv, "apr_proc_detach"); } #if defined(WIN32) || defined(OS2) || defined(NETWARE) #error "Please implement me." #else while (--num_to_start >= 0) { rv = apr_proc_fork(&proc, pool); if (rv == APR_INCHILD) { apr_os_file_t oft = 0; apr_os_sock_t oskt; /* Ok, so we need a file that has file descriptor 0 (which * FastCGI wants), but points to our socket. This isn't really * possible in APR, so we cheat a bit. I have no idea how to * do this on a non-unix platform, so for now this is platform * specific. Ick. * * Note that this has to happen post-detach, otherwise fd 0 * gets closed during apr_proc_detach and it's all for nothing. * * Unfortunately, doing this post detach means we have no way * to let anyone know if there's a problem at this point :( */ rv = apr_os_file_put(&infd, &oft, APR_READ | APR_WRITE, pool); if (rv) { exit(EXIT_FAILURE); } rv = apr_os_sock_get(&oskt, skt); if (rv) { exit(EXIT_FAILURE); } rv = apr_os_file_put(&skwrapper, &oskt, APR_READ | APR_WRITE, pool); if (rv) { exit(EXIT_FAILURE); } rv = apr_file_dup2(infd, skwrapper, pool); if (rv) { exit(EXIT_FAILURE); } /* XXX Can't use apr_proc_create because there's no way to get * infd into the procattr without going through another dup2, * which means by the time it gets to the fastcgi process it * is no longer fd 0, so it doesn't work. Sigh. */ execl(command, command, NULL); } else if (rv == APR_INPARENT) { if (num_to_start == 0) { apr_socket_close(skt); } } else { exit_error(rv, "apr_proc_fork"); } } #endif return EXIT_SUCCESS; }
int main(int argc, const char * const argv[]) { apr_pool_t *pool; apr_status_t rv; char errbuf[MAX_STRING_LEN]; int need_file = 1; int need_user = 1; int need_pwd = 1; int need_cmnt = 0; int changed = 0; int cmd = HTDBM_MAKE; int i, ret, args_left = 2; apr_getopt_t *state; char opt; const char *opt_arg; apr_app_initialize(&argc, &argv, NULL); atexit(terminate); if ((rv = htdbm_init(&pool, &h)) != APR_SUCCESS) { fprintf(stderr, "Unable to initialize htdbm terminating!\n"); apr_strerror(rv, errbuf, sizeof(errbuf)); exit(1); } rv = apr_getopt_init(&state, pool, argc, argv); if (rv != APR_SUCCESS) exit(ERR_SYNTAX); while ((rv = apr_getopt(state, "cnmspdBbDivxlC:T:", &opt, &opt_arg)) == APR_SUCCESS) { switch (opt) { case 'c': h->create = 1; break; case 'n': need_file = 0; cmd = HTDBM_NOFILE; args_left--; break; case 'l': need_pwd = 0; need_user = 0; cmd = HTDBM_LIST; h->rdonly = 1; args_left--; break; case 't': need_cmnt = 1; args_left++; break; case 'T': h->type = apr_pstrdup(h->ctx.pool, opt_arg); break; case 'v': h->rdonly = 1; cmd = HTDBM_VERIFY; break; case 'x': need_pwd = 0; cmd = HTDBM_DELETE; break; default: ret = parse_common_options(&h->ctx, opt, opt_arg); if (ret) { fprintf(stderr, "Error: %s\n", h->ctx.errstr); exit(ret); } } } if (h->ctx.passwd_src == PW_ARG) { need_pwd = 0; args_left++; } /* * Make sure we still have exactly the right number of arguments left * (the filename, the username, and possibly the password if -b was * specified). */ i = state->ind; if (rv != APR_EOF || argc - i != args_left) htdbm_usage(); if (need_file) { h->filename = apr_pstrdup(h->ctx.pool, argv[i++]); if ((rv = htdbm_open(h)) != APR_SUCCESS) { fprintf(stderr, "Error opening database %s\n", h->filename); apr_strerror(rv, errbuf, sizeof(errbuf)); fprintf(stderr,"%s\n",errbuf); exit(ERR_FILEPERM); } } if (need_user) { h->username = apr_pstrdup(pool, argv[i++]); if (htdbm_valid_username(h) != APR_SUCCESS) exit(ERR_BADUSER); } if (h->ctx.passwd_src == PW_ARG) h->ctx.passwd = apr_pstrdup(pool, argv[i++]); if (need_pwd) { ret = get_password(&h->ctx); if (ret) { fprintf(stderr, "Error: %s\n", h->ctx.errstr); exit(ret); } } if (need_cmnt) h->comment = apr_pstrdup(pool, argv[i++]); switch (cmd) { case HTDBM_VERIFY: if ((rv = htdbm_verify(h)) != APR_SUCCESS) { if (APR_STATUS_IS_ENOENT(rv)) { fprintf(stderr, "The user '%s' could not be found in database\n", h->username); exit(ERR_BADUSER); } else { fprintf(stderr, "Password mismatch for user '%s'\n", h->username); exit(ERR_PWMISMATCH); } } else fprintf(stderr, "Password validated for user '%s'\n", h->username); break; case HTDBM_DELETE: if (htdbm_del(h) != APR_SUCCESS) { fprintf(stderr, "Cannot find user '%s' in database\n", h->username); exit(ERR_BADUSER); } h->username = NULL; changed = 1; break; case HTDBM_LIST: htdbm_list(h); break; default: ret = htdbm_make(h); if (ret) exit(ret); break; } if (need_file && !h->rdonly) { if ((rv = htdbm_save(h, &changed)) != APR_SUCCESS) { apr_strerror(rv, errbuf, sizeof(errbuf)); exit(ERR_FILEPERM); } fprintf(stdout, "Database %s %s.\n", h->filename, h->create ? "created" : (changed ? "modified" : "updated")); } if (cmd == HTDBM_NOFILE) { if (!need_cmnt) { fprintf(stderr, "%s:%s\n", h->username, h->ctx.passwd); } else { fprintf(stderr, "%s:%s:%s\n", h->username, h->ctx.passwd, h->comment); } } htdbm_terminate(h); return 0; /* Suppress compiler warning. */ }
int main(int argc, const char *const argv[]) { apr_pool_t *pool; apr_status_t rv = APR_SUCCESS; apr_getopt_t *opt; const char *opt_arg; char ch; apr_file_t *infile; apr_dbm_t *outdbm; apr_app_initialize(&argc, &argv, NULL); atexit(apr_terminate); verbose = 0; format = NULL; input = NULL; output = NULL; apr_pool_create(&pool, NULL); if (argc) { shortname = apr_filepath_name_get(argv[0]); } else { shortname = "httxt2dbm"; } apr_file_open_stderr(&errfile, pool); rv = apr_getopt_init(&opt, pool, argc, argv); if (rv != APR_SUCCESS) { apr_file_printf(errfile, "Error: apr_getopt_init failed."NL NL); return 1; } if (argc <= 1) { usage(); return 1; } while ((rv = apr_getopt(opt, "vf::i::o::", &ch, &opt_arg)) == APR_SUCCESS) { switch (ch) { case 'v': if (verbose) { apr_file_printf(errfile, "Error: -v can only be passed once" NL NL); usage(); return 1; } verbose = 1; break; case 'f': if (format) { apr_file_printf(errfile, "Error: -f can only be passed once" NL NL); usage(); return 1; } format = apr_pstrdup(pool, opt_arg); break; case 'i': if (input) { apr_file_printf(errfile, "Error: -i can only be passed once" NL NL); usage(); return 1; } input = apr_pstrdup(pool, opt_arg); break; case 'o': if (output) { apr_file_printf(errfile, "Error: -o can only be passed once" NL NL); usage(); return 1; } output = apr_pstrdup(pool, opt_arg); break; } } if (rv != APR_EOF) { apr_file_printf(errfile, "Error: Parsing Arguments Failed" NL NL); usage(); return 1; } if (!input) { apr_file_printf(errfile, "Error: No input file specified." NL NL); usage(); return 1; } if (!output) { apr_file_printf(errfile, "Error: No output DBM specified." NL NL); usage(); return 1; } if (!format) { format = "default"; } if (verbose) { apr_file_printf(errfile, "DBM Format: %s"NL, format); } if (!strcmp(input, "-")) { rv = apr_file_open_stdin(&infile, pool); } else { rv = apr_file_open(&infile, input, APR_READ|APR_BUFFERED, APR_OS_DEFAULT, pool); } if (rv != APR_SUCCESS) { apr_file_printf(errfile, "Error: Cannot open input file '%s': (%d) %s" NL NL, input, rv, apr_strerror(rv, errbuf, sizeof(errbuf))); return 1; } if (verbose) { apr_file_printf(errfile, "Input File: %s"NL, input); } rv = apr_dbm_open_ex(&outdbm, format, output, APR_DBM_RWCREATE, APR_OS_DEFAULT, pool); if (APR_STATUS_IS_ENOTIMPL(rv)) { apr_file_printf(errfile, "Error: The requested DBM Format '%s' is not available." NL NL, format); return 1; } if (rv != APR_SUCCESS) { apr_file_printf(errfile, "Error: Cannot open output DBM '%s': (%d) %s" NL NL, output, rv, apr_strerror(rv, errbuf, sizeof(errbuf))); return 1; } if (verbose) { apr_file_printf(errfile, "DBM File: %s"NL, output); } rv = to_dbm(outdbm, infile, pool); if (rv != APR_SUCCESS) { apr_file_printf(errfile, "Error: Converting to DBM: (%d) %s" NL NL, rv, apr_strerror(rv, errbuf, sizeof(errbuf))); return 1; } apr_dbm_close(outdbm); if (verbose) { apr_file_printf(errfile, "Conversion Complete." NL); } return 0; }
/* Compile with * $> export APR_LIBS="`apr-1-config --cflags --cppflags --includes --ldflags --link-ld --libs`" * $> export APU_LIBS="`apu-1-config --includes --ldflags --link-ld --libs`" * $> gcc aprGetoptLong.c -o aprGetoptLong $APR_LIBS $APU_LIBS */ int main(int argc, const char * const *argv) { apr_pool_t *p = NULL; apr_getopt_t *cmdLineArgs = NULL; apr_status_t rv; int optChar = 0; const char *optArg = NULL; /* Will hold the position for the non optional * args in the APR parsed argv */ int processedOptions = 0; /* cleanly handle fileIO this time */ apr_file_t *out = NULL; apr_file_t *err = NULL; /* Let's handle long opts too */ const apr_getopt_option_t longOpts[] = {{"help", 'h', 0, "Show help"}, {"choose", 'c', 1, "Choose something"}}; /* init APR, create memory pool */ apr_app_initialize(&argc, &argv, NULL); atexit(apr_terminate); apr_pool_create(&p, NULL); /* Open stdin, stderr */ apr_file_open_stdout(&out, p); apr_file_open_stderr(&err, p); /* init APRs getopt */ apr_getopt_init(&cmdLineArgs, p, argc, argv); /* Allow options to be added after arguments */ cmdLineArgs->interleave = 1; /* Now step through the options given */ while ((rv = apr_getopt_long(cmdLineArgs, longOpts, &optChar, &optArg)) == APR_SUCCESS) { switch(optChar) { case 'h': apr_file_printf(out, "Read option h ...\n"); break; case 'c': apr_file_printf(out, "Read option c with argument %s \n", optArg); break; default: apr_file_printf(out, "Default reached ...\n"); } } if (APR_STATUS_IS_BADCH(rv)) { apr_file_printf(err, "Read bad option ...\n"); } processedOptions = cmdLineArgs->ind; /* Now spit out non options */ while (processedOptions < argc) { apr_file_printf(out, "Non opt arg: %s\n", cmdLineArgs->argv[processedOptions++]); } apr_pool_destroy(p); return 0; }
int main(int argc, const char * const argv[]) { apr_file_t *f; apr_status_t rv; char tn[] = "htdigest.tmp.XXXXXX"; char *dirname; char user[MAX_STRING_LEN]; char realm[MAX_STRING_LEN]; char line[MAX_STRING_LEN]; char l[MAX_STRING_LEN]; char w[MAX_STRING_LEN]; char x[MAX_STRING_LEN]; int found; apr_app_initialize(&argc, &argv, NULL); atexit(terminate); apr_pool_create(&cntxt, NULL); apr_file_open_stderr(&errfile, cntxt); #if APR_CHARSET_EBCDIC rv = apr_xlate_open(&to_ascii, "ISO8859-1", APR_DEFAULT_CHARSET, cntxt); if (rv) { apr_file_printf(errfile, "apr_xlate_open(): %s (%d)\n", apr_strerror(rv, line, sizeof(line)), rv); exit(1); } #endif apr_signal(SIGINT, (void (*)(int)) interrupted); if (argc == 5) { if (strcmp(argv[1], "-c")) usage(); rv = apr_file_open(&f, argv[2], APR_WRITE | APR_CREATE, APR_OS_DEFAULT, cntxt); if (rv != APR_SUCCESS) { char errmsg[120]; apr_file_printf(errfile, "Could not open passwd file %s for writing: %s\n", argv[2], apr_strerror(rv, errmsg, sizeof errmsg)); exit(1); } apr_file_printf(errfile, "Adding password for %s in realm %s.\n", argv[4], argv[3]); add_password(argv[4], argv[3], f); apr_file_close(f); exit(0); } else if (argc != 4) usage(); if (apr_temp_dir_get((const char**)&dirname, cntxt) != APR_SUCCESS) { apr_file_printf(errfile, "%s: could not determine temp dir\n", argv[0]); exit(1); } dirname = apr_psprintf(cntxt, "%s/%s", dirname, tn); if (apr_file_mktemp(&tfp, dirname, 0, cntxt) != APR_SUCCESS) { apr_file_printf(errfile, "Could not open temp file %s.\n", dirname); exit(1); } if (apr_file_open(&f, argv[1], APR_READ, APR_OS_DEFAULT, cntxt) != APR_SUCCESS) { apr_file_printf(errfile, "Could not open passwd file %s for reading.\n", argv[1]); apr_file_printf(errfile, "Use -c option to create new one.\n"); cleanup_tempfile_and_exit(1); } apr_cpystrn(user, argv[3], sizeof(user)); apr_cpystrn(realm, argv[2], sizeof(realm)); found = 0; while (!(get_line(line, MAX_STRING_LEN, f))) { if (found || (line[0] == '#') || (!line[0])) { putline(tfp, line); continue; } strcpy(l, line); getword(w, l, ':'); getword(x, l, ':'); if (strcmp(user, w) || strcmp(realm, x)) { putline(tfp, line); continue; } else { apr_file_printf(errfile, "Changing password for user %s in realm %s\n", user, realm); add_password(user, realm, tfp); found = 1; } } if (!found) { apr_file_printf(errfile, "Adding user %s in realm %s\n", user, realm); add_password(user, realm, tfp); } apr_file_close(f); /* The temporary file has all the data, just copy it to the new location. */ if (apr_file_copy(dirname, argv[1], APR_FILE_SOURCE_PERMS, cntxt) != APR_SUCCESS) { apr_file_printf(errfile, "%s: unable to update file %s\n", argv[0], argv[1]); } apr_file_close(tfp); return 0; }
int main (int argc, const char * const argv[]) { char buf[BUFSIZE]; apr_size_t nRead, nWrite; apr_file_t *f_stdin; apr_file_t *f_stdout; apr_getopt_t *opt; apr_status_t rv; char c; const char *opt_arg; const char *err = NULL; #if APR_FILES_AS_SOCKETS apr_pollfd_t pollfd = { 0 }; apr_status_t pollret = APR_SUCCESS; int polltimeout; #endif apr_app_initialize(&argc, &argv, NULL); atexit(apr_terminate); memset(&config, 0, sizeof config); memset(&status, 0, sizeof status); status.rotateReason = ROTATE_NONE; apr_pool_create(&status.pool, NULL); apr_getopt_init(&opt, status.pool, argc, argv); #if APR_FILES_AS_SOCKETS while ((rv = apr_getopt(opt, "lL:p:ftvecn:", &c, &opt_arg)) == APR_SUCCESS) { #else while ((rv = apr_getopt(opt, "lL:p:ftven:", &c, &opt_arg)) == APR_SUCCESS) { #endif switch (c) { case 'l': config.use_localtime = 1; break; case 'L': config.linkfile = opt_arg; break; case 'p': config.postrotate_prog = opt_arg; break; case 'f': config.force_open = 1; break; case 't': config.truncate = 1; break; case 'v': config.verbose = 1; break; case 'e': config.echo = 1; break; #if APR_FILES_AS_SOCKETS case 'c': config.create_empty = 1; break; #endif case 'n': config.num_files = atoi(opt_arg); status.fileNum = -1; break; } } if (rv != APR_EOF) { usage(argv[0], NULL /* specific error message already issued */ ); } /* * After the initial flags we need 2 to 4 arguments, * the file name, either the rotation interval time or size * or both of them, and optionally the UTC offset. */ if ((argc - opt->ind < 2) || (argc - opt->ind > 4) ) { usage(argv[0], "Incorrect number of arguments"); } config.szLogRoot = argv[opt->ind++]; /* Read in the remaining flags, namely time, size and UTC offset. */ for(; opt->ind < argc; opt->ind++) { if ((err = get_time_or_size(&config, argv[opt->ind], opt->ind < argc - 1 ? 0 : 1)) != NULL) { usage(argv[0], err); } } config.use_strftime = (strchr(config.szLogRoot, '%') != NULL); if (config.use_strftime && config.num_files > 0) { fprintf(stderr, "Cannot use -n with %% in filename\n"); exit(1); } if (status.fileNum == -1 && config.num_files < 1) { fprintf(stderr, "Invalid -n argument\n"); exit(1); } if (apr_file_open_stdin(&f_stdin, status.pool) != APR_SUCCESS) { fprintf(stderr, "Unable to open stdin\n"); exit(1); } if (apr_file_open_stdout(&f_stdout, status.pool) != APR_SUCCESS) { fprintf(stderr, "Unable to open stdout\n"); exit(1); } /* * Write out result of config parsing if verbose is set. */ if (config.verbose) { dumpConfig(&config); } #if APR_FILES_AS_SOCKETS if (config.create_empty && config.tRotation) { pollfd.p = status.pool; pollfd.desc_type = APR_POLL_FILE; pollfd.reqevents = APR_POLLIN; pollfd.desc.f = f_stdin; } #endif /* * Immediately open the logfile as we start, if we were forced * to do so via '-f'. */ if (config.force_open) { doRotate(&config, &status); } for (;;) { nRead = sizeof(buf); #if APR_FILES_AS_SOCKETS if (config.create_empty && config.tRotation) { polltimeout = status.tLogEnd ? status.tLogEnd - get_now(&config) : config.tRotation; if (polltimeout <= 0) { pollret = APR_TIMEUP; } else { pollret = apr_poll(&pollfd, 1, &pollret, apr_time_from_sec(polltimeout)); } } if (pollret == APR_SUCCESS) { rv = apr_file_read(f_stdin, buf, &nRead); if (APR_STATUS_IS_EOF(rv)) { break; } else if (rv != APR_SUCCESS) { exit(3); } } else if (pollret == APR_TIMEUP) { *buf = 0; nRead = 0; } else { fprintf(stderr, "Unable to poll stdin\n"); exit(5); } #else /* APR_FILES_AS_SOCKETS */ rv = apr_file_read(f_stdin, buf, &nRead); if (APR_STATUS_IS_EOF(rv)) { break; } else if (rv != APR_SUCCESS) { exit(3); } #endif /* APR_FILES_AS_SOCKETS */ checkRotate(&config, &status); if (status.rotateReason != ROTATE_NONE) { doRotate(&config, &status); } nWrite = nRead; rv = apr_file_write_full(status.current.fd, buf, nWrite, &nWrite); if (nWrite != nRead) { apr_off_t cur_offset; cur_offset = 0; if (apr_file_seek(status.current.fd, APR_CUR, &cur_offset) != APR_SUCCESS) { cur_offset = -1; } status.nMessCount++; apr_snprintf(status.errbuf, sizeof status.errbuf, "Error %d writing to log file at offset %" APR_OFF_T_FMT ". " "%10d messages lost (%pm)\n", rv, cur_offset, status.nMessCount, &rv); truncate_and_write_error(&status); } else { status.nMessCount++; } if (config.echo) { if (apr_file_write_full(f_stdout, buf, nRead, &nWrite)) { fprintf(stderr, "Unable to write to stdout\n"); exit(4); } } } return 0; /* reached only at stdin EOF. */ }
int main(int argc, const char * const argv[]) { int rc; int stat = 0; const char *ip = NULL; char *msg = NULL; qos_geo_t *geo; int size; const char *db = NULL; apr_table_t *entries; apr_pool_t *pool; const char *cmd = strrchr(argv[0], '/'); apr_app_initialize(&argc, &argv, NULL); apr_pool_create(&pool, NULL); entries = apr_table_make(pool, 100); if(cmd == NULL) { cmd = (char *)argv[0]; } else { cmd++; } argc--; argv++; while(argc >= 1) { if(strcmp(*argv, "-d") == 0) { if (--argc >= 1) { db = *(++argv); } } else if(strcmp(*argv, "-ip") == 0) { if (--argc >= 1) { ip = *(++argv); } } else if(strcmp(*argv, "-s") == 0) { stat = 1; } else if(strcmp(*argv, "-l") == 0) { m_inject = 1; } else if(strcmp(*argv,"-h") == 0) { usage(cmd, 0); } else if(strcmp(*argv,"--help") == 0) { usage(cmd, 0); } else if(strcmp(*argv,"-?") == 0) { usage(cmd, 0); } else if(strcmp(*argv,"--man") == 0) { usage(cmd, 1); } else { usage(cmd, 0); } argc--; argv++; } if(db == NULL) { usage(cmd, 0); } rc = nice(10); if(rc == -1) { fprintf(stderr, "ERROR, failed to change nice value: %s\n", strerror(errno)); } geo = qos_loadgeo(pool, db, &size, &msg); if(geo == NULL || msg != NULL) { fprintf(stderr, "failed to load database: %s\n", msg ? msg : "-"); exit(1); } if(m_inject) { exit(0); } if(ip) { qos_geo_t *pB; unsigned long search = qos_geo_str2long(pool, ip); printf("search %lu: ", search); pB = bsearch(&search, geo, size, sizeof(qos_geo_t), qos_geo_comp); if(pB) { printf("%s\n", pB->country); } else { printf("n/a\n"); } return 0; } // start reading from stdin { char prev; qos_geo_t *pB; apr_pool_t *tmp; char line[HUGE_STRING_LEN]; regex_t preg; regex_t preg2; regmatch_t ma[MAX_REG_MATCH]; apr_pool_create(&tmp, NULL); if(regcomp(&preg, IPPATTERN, REG_EXTENDED)) { exit(1); } regcomp(&preg2, IPPATTERN2, REG_EXTENDED); while(fgets(line, sizeof(line), stdin) != NULL) { int match = regexec(&preg, line, MAX_REG_MATCH, ma, 0); if(match != 0) { char *dx = strchr(line, ';'); if(dx && ((dx - line) <= 15)) { // file starts probably with <ip>; => a qslog -pc file? match = regexec(&preg2, line, MAX_REG_MATCH, ma, 0); } } if(match == 0) { unsigned long search; prev = line[ma[1].rm_eo]; line[ma[1].rm_eo] = '\0'; search = qos_geo_str2long(tmp, &line[ma[1].rm_so]); apr_pool_clear(tmp); pB = bsearch(&search, geo, size, sizeof(qos_geo_t), qos_geo_comp); if(stat) { /* creates a single statistic entry for each country (used to collect requests per source country) */ if(pB) { qos_geo_stat_t *s = (qos_geo_stat_t *)apr_table_get(entries, pB->country); if(s == NULL) { s = apr_pcalloc(pool, sizeof(qos_geo_stat_t)); s->num = 0; s->c = pB->c; apr_table_addn(entries, apr_pstrdup(pool, pB->country), (char *)s); } s->num++; } } else { /* modifies each log line inserting the country code */ char cr = prev; char delw[2]; char delx[2]; delw[1] = '\0'; delw[0] = ' '; delx[1] = '\0'; delx[0] = ' '; if(line[ma[1].rm_eo+1] == ' ') { delx[0] = '\0'; } if(line[ma[1].rm_eo+1] == ';') { delx[0] = ';'; } if(prev <= CR) { prev = ' '; } if(prev == ' ') { delw[0] = '\0'; } if(prev == ';') { delw[0] = '\0'; delx[0] = ';'; } if(pB) { printf("%s%c%s%s%s%s", line, prev, delw, pB->country, delx, &line[ma[1].rm_eo+1]); } else { printf("%s%c%s--%s%s", line, prev, delw, delx, &line[ma[1].rm_eo+1]); } if(cr <= CR) { printf("\n"); } } } else { printf("%s", line); } fflush(stdout); } if(stat) { int i; apr_table_entry_t *entry = (apr_table_entry_t *)apr_table_elts(entries)->elts; for(i = 0; i < apr_table_elts(entries)->nelts; i++) { qos_geo_stat_t *s = (qos_geo_stat_t *)entry[i].val; printf("%7.d %s %s\n", s->num, entry[i].key, s->c ? s->c : ""); } } } return 0; }
int main(int argc, const char * const argv[]) { apr_pool_t *pool; apr_status_t rv; apr_size_t l; char pwi[MAX_STRING_LEN]; char pwc[MAX_STRING_LEN]; char errbuf[MAX_STRING_LEN]; const char *arg; int need_file = 1; int need_user = 1; int need_pwd = 1; int need_cmnt = 0; int pwd_supplied = 0; int changed = 0; int cmd = HTDBM_MAKE; int i; int args_left = 2; apr_app_initialize(&argc, &argv, NULL); atexit(terminate); if ((rv = htdbm_init(&pool, &h)) != APR_SUCCESS) { fprintf(stderr, "Unable to initialize htdbm terminating!\n"); apr_strerror(rv, errbuf, sizeof(errbuf)); exit(1); } /* * Preliminary check to make sure they provided at least * three arguments, we'll do better argument checking as * we parse the command line. */ if (argc < 3) htdbm_usage(); /* * Go through the argument list and pick out any options. They * have to precede any other arguments. */ for (i = 1; i < argc; i++) { arg = argv[i]; if (*arg != '-') break; while (*++arg != '\0') { switch (*arg) { case 'b': pwd_supplied = 1; need_pwd = 0; args_left++; break; case 'c': h->create = 1; break; case 'n': need_file = 0; cmd = HTDBM_NOFILE; args_left--; break; case 'l': need_pwd = 0; need_user = 0; cmd = HTDBM_LIST; h->rdonly = 1; args_left--; break; case 't': need_cmnt = 1; args_left++; break; case 'T': h->type = apr_pstrdup(h->pool, ++arg); while (*arg != '\0') ++arg; --arg; /* so incrementing this in the loop with find a null */ break; case 'v': h->rdonly = 1; cmd = HTDBM_VERIFY; break; case 'x': need_pwd = 0; cmd = HTDBM_DELETE; break; case 'm': h->alg = ALG_APMD5; break; case 'p': h->alg = ALG_PLAIN; break; case 's': h->alg = ALG_APSHA; break; #if (!(defined(WIN32) || defined(TPF) || defined(NETWARE))) case 'd': h->alg = ALG_CRYPT; break; #endif default: htdbm_usage(); break; } } } /* * Make sure we still have exactly the right number of arguments left * (the filename, the username, and possibly the password if -b was * specified). */ if ((argc - i) != args_left) htdbm_usage(); if (!need_file) i--; else { h->filename = apr_pstrdup(h->pool, argv[i]); if ((rv = htdbm_open(h)) != APR_SUCCESS) { fprintf(stderr, "Error opening database %s\n", argv[i]); apr_strerror(rv, errbuf, sizeof(errbuf)); fprintf(stderr,"%s\n",errbuf); exit(ERR_FILEPERM); } } if (need_user) { h->username = apr_pstrdup(pool, argv[i+1]); if (htdbm_valid_username(h) != APR_SUCCESS) exit(ERR_BADUSER); } if (pwd_supplied) h->userpass = apr_pstrdup(pool, argv[i+2]); if (need_pwd) { l = sizeof(pwc); if (apr_password_get("Enter password : "******"Password too long\n"); exit(ERR_OVERFLOW); } l = sizeof(pwc); if (apr_password_get("Re-type password : "******"Password too long\n"); exit(ERR_OVERFLOW); } if (strcmp(pwi, pwc) != 0) { fprintf(stderr, "Password verification error\n"); exit(ERR_PWMISMATCH); } h->userpass = apr_pstrdup(pool, pwi); } if (need_cmnt && pwd_supplied) h->comment = apr_pstrdup(pool, argv[i+3]); else if (need_cmnt) h->comment = apr_pstrdup(pool, argv[i+2]); switch (cmd) { case HTDBM_VERIFY: if ((rv = htdbm_verify(h)) != APR_SUCCESS) { if(rv == APR_ENOENT) { fprintf(stderr, "The user '%s' could not be found in database\n", h->username); exit(ERR_BADUSER); } else { fprintf(stderr, "Password mismatch for user '%s'\n", h->username); exit(ERR_PWMISMATCH); } } else fprintf(stderr, "Password validated for user '%s'\n", h->username); break; case HTDBM_DELETE: if (htdbm_del(h) != APR_SUCCESS) { fprintf(stderr, "Cannot find user '%s' in database\n", h->username); exit(ERR_BADUSER); } h->username = NULL; changed = 1; break; case HTDBM_LIST: htdbm_list(h); break; default: htdbm_make(h); break; } if (need_file && !h->rdonly) { if ((rv = htdbm_save(h, &changed)) != APR_SUCCESS) { apr_strerror(rv, errbuf, sizeof(errbuf)); exit(ERR_FILEPERM); } fprintf(stdout, "Database %s %s.\n", h->filename, h->create ? "created" : (changed ? "modified" : "updated")); } if (cmd == HTDBM_NOFILE) { if (!need_cmnt) { fprintf(stderr, "%s:%s\n", h->username, h->userpass); } else { fprintf(stderr, "%s:%s:%s\n", h->username, h->userpass, h->comment); } } htdbm_terminate(h); return 0; /* Suppress compiler warning. */ }
/* * Let's do it. We end up doing a lot of file opening and closing, * but what do we care? This application isn't run constantly. */ int main(int argc, const char * const argv[]) { apr_file_t *fpw = NULL; char record[MAX_STRING_LEN]; char line[MAX_STRING_LEN]; char *password = NULL; char *pwfilename = NULL; char *user = NULL; char tn[] = "htpasswd.tmp.XXXXXX"; char *dirname; char *scratch, cp[MAX_STRING_LEN]; int found = 0; int i; int alg = ALG_APMD5; int mask = 0; apr_pool_t *pool; int existing_file = 0; #if APR_CHARSET_EBCDIC apr_status_t rv; apr_xlate_t *to_ascii; #endif apr_app_initialize(&argc, &argv, NULL); atexit(terminate); apr_pool_create(&pool, NULL); apr_file_open_stderr(&errfile, pool); #if APR_CHARSET_EBCDIC rv = apr_xlate_open(&to_ascii, "ISO-8859-1", APR_DEFAULT_CHARSET, pool); if (rv) { apr_file_printf(errfile, "apr_xlate_open(to ASCII)->%d" NL, rv); exit(1); } rv = apr_SHA1InitEBCDIC(to_ascii); if (rv) { apr_file_printf(errfile, "apr_SHA1InitEBCDIC()->%d" NL, rv); exit(1); } rv = apr_MD5InitEBCDIC(to_ascii); if (rv) { apr_file_printf(errfile, "apr_MD5InitEBCDIC()->%d" NL, rv); exit(1); } #endif /*APR_CHARSET_EBCDIC*/ check_args(pool, argc, argv, &alg, &mask, &user, &pwfilename, &password); #if defined(WIN32) || defined(NETWARE) if (alg == ALG_CRYPT) { alg = ALG_APMD5; apr_file_printf(errfile, "Automatically using MD5 format." NL); } #endif #if (!(defined(WIN32) || defined(TPF) || defined(NETWARE))) if (alg == ALG_PLAIN) { apr_file_printf(errfile,"Warning: storing passwords as plain text " "might just not work on this platform." NL); } #endif /* * Only do the file checks if we're supposed to frob it. */ if (!(mask & APHTP_NOFILE)) { existing_file = exists(pwfilename, pool); if (existing_file) { /* * Check that this existing file is readable and writable. */ if (!accessible(pool, pwfilename, APR_READ | APR_APPEND)) { apr_file_printf(errfile, "%s: cannot open file %s for " "read/write access" NL, argv[0], pwfilename); exit(ERR_FILEPERM); } } else { /* * Error out if -c was omitted for this non-existant file. */ if (!(mask & APHTP_NEWFILE)) { apr_file_printf(errfile, "%s: cannot modify file %s; use '-c' to create it" NL, argv[0], pwfilename); exit(ERR_FILEPERM); } /* * As it doesn't exist yet, verify that we can create it. */ if (!accessible(pool, pwfilename, APR_CREATE | APR_WRITE)) { apr_file_printf(errfile, "%s: cannot create file %s" NL, argv[0], pwfilename); exit(ERR_FILEPERM); } } } /* * All the file access checks (if any) have been made. Time to go to work; * try to create the record for the username in question. If that * fails, there's no need to waste any time on file manipulations. * Any error message text is returned in the record buffer, since * the mkrecord() routine doesn't have access to argv[]. */ if (!(mask & APHTP_DELUSER)) { i = mkrecord(user, record, sizeof(record) - 1, password, alg); if (i != 0) { apr_file_printf(errfile, "%s: %s" NL, argv[0], record); exit(i); } if (mask & APHTP_NOFILE) { printf("%s" NL, record); exit(0); } } /* * We can access the files the right way, and we have a record * to add or update. Let's do it.. */ if (apr_temp_dir_get((const char**)&dirname, pool) != APR_SUCCESS) { apr_file_printf(errfile, "%s: could not determine temp dir" NL, argv[0]); exit(ERR_FILEPERM); } dirname = apr_psprintf(pool, "%s/%s", dirname, tn); if (apr_file_mktemp(&ftemp, dirname, 0, pool) != APR_SUCCESS) { apr_file_printf(errfile, "%s: unable to create temporary file %s" NL, argv[0], dirname); exit(ERR_FILEPERM); } /* * If we're not creating a new file, copy records from the existing * one to the temporary file until we find the specified user. */ if (existing_file && !(mask & APHTP_NEWFILE)) { if (apr_file_open(&fpw, pwfilename, APR_READ | APR_BUFFERED, APR_OS_DEFAULT, pool) != APR_SUCCESS) { apr_file_printf(errfile, "%s: unable to read file %s" NL, argv[0], pwfilename); exit(ERR_FILEPERM); } while (apr_file_gets(line, sizeof(line), fpw) == APR_SUCCESS) { char *colon; strcpy(cp, line); scratch = cp; while (apr_isspace(*scratch)) { ++scratch; } if (!*scratch || (*scratch == '#')) { putline(ftemp, line); continue; } /* * See if this is our user. */ colon = strchr(scratch, ':'); if (colon != NULL) { *colon = '\0'; } else { /* * If we've not got a colon on the line, this could well * not be a valid htpasswd file. * We should bail at this point. */ apr_file_printf(errfile, "%s: The file %s does not appear " "to be a valid htpasswd file." NL, argv[0], pwfilename); apr_file_close(fpw); exit(ERR_INVALID); } if (strcmp(user, scratch) != 0) { putline(ftemp, line); continue; } else { if (!(mask & APHTP_DELUSER)) { /* We found the user we were looking for. * Add him to the file. */ apr_file_printf(errfile, "Updating "); putline(ftemp, record); found++; } else { /* We found the user we were looking for. * Delete them from the file. */ apr_file_printf(errfile, "Deleting "); found++; } } } apr_file_close(fpw); } if (!found && !(mask & APHTP_DELUSER)) { apr_file_printf(errfile, "Adding "); putline(ftemp, record); } else if (!found && (mask & APHTP_DELUSER)) { apr_file_printf(errfile, "User %s not found" NL, user); exit(0); } apr_file_printf(errfile, "password for user %s" NL, user); /* The temporary file has all the data, just copy it to the new location. */ if (apr_file_copy(dirname, pwfilename, APR_FILE_SOURCE_PERMS, pool) != APR_SUCCESS) { apr_file_printf(errfile, "%s: unable to update file %s" NL, argv[0], pwfilename); exit(ERR_FILEPERM); } apr_file_close(ftemp); return 0; }
int main(int argc, const char * const *argv) { apr_pool_t *pool; const char *arg; UploaderConfig *config; int status; apr_size_t bench_count; apr_app_initialize(&argc, &argv, NULL); apr_pool_create(&pool, NULL); config = NULL; status = 0; try { arg = getenv("PATH_INFO"); if (arg == NULL) { std::cout << "Location: http://"; std::cout << CGIResponse::get_env(pool, "SERVER_NAME"); if ((strcmp(CGIResponse::get_env(pool, "SERVER_PORT"), "80") != 0)) { std::cout << ":" << CGIResponse::get_env(pool, "SERVER_PORT"); } std::cout << CGIResponse::get_env(pool, "SCRIPT_NAME") << "/\r\n\r\n"; return EXIT_SUCCESS; } config = CGIConfigReader::read(pool, CONF_FILE_NAME); config->child_init(); // ベンチマーク用 bench_count = atoi(getenv("UPLOADER_BENCH")); if (bench_count == 0) { bench_count++; } STRACE_MARKER(); for (apr_size_t i = 0; i < bench_count; i++) { TemporaryPool temp_pool(pool); CGIResponse::Handle handle(temp_pool.get()); status = uploader_command_handler<CGIResponse> (&handle, config, arg); } STRACE_MARKER(); config->finalize(); apr_pool_destroy(pool); apr_terminate(); return status; } catch(const char *message) { // できれば Internal Server Error にしたいけど,問い合わせが多 // くなりそうなので... std::cout << "Content-type: text/html; charset=UTF-8\r\n\r\n"; std::cout << "Fatal Error: " << message << std::endl; if (config != NULL) { config->finalize(); } apr_pool_destroy(pool); apr_terminate(); return EXIT_FAILURE; } }