コード例 #1
0
ファイル: main.c プロジェクト: MuteLang/lair
int main(int argc, char *argv[]) {
	if (argc < 2) {
		_print_usage(argv[0]);
		exit(0);
	}

	/* The file we're going to load in: */
	const char *file_path = argv[1];
	/* Where we're going to store our loaded buffer: */
	char *buf = NULL;
	size_t buf_siz = 0;

	buf = lair_load_file(file_path, &buf_siz);
	if (buf == NULL) {
		error_and_die(ERR_RUNTIME, "Could not load file.");
		return 1;
	}

	int rc = lair_execute(buf, buf_siz);
	if (rc != 0) {
		error_and_die(ERR_RUNTIME, "Could not execute.");
		return 1;
	}

	lair_unload_file(buf, buf_siz);
	return 0;
}
コード例 #2
0
ファイル: h3mdllembed.c プロジェクト: Dergash/homm3tools
int main(int argc, char **argv)
{
    char *output_file = NULL;
    size_t len = 0;
    h3mlib_ctx_t h3m = NULL;

    if (argc != 3) {
        _print_usage();
        return 1;
    }

    if (0 != h3m_read(&h3m, argv[1])) {
        printf("[!] Failed to open %s!", argv[1]);
        return 1;
    }
    
    if (0 != h3m_modembed_set_dll(h3m, argv[2])) {
        printf("[!] Failed to embed DLL %s!", argv[2]);
        h3m_exit(&h3m);
        return 1;
    }

    len = strlen(argv[1]) + sizeof(H3COMPLETE_SUFFIX);
    output_file = calloc(len, 1);
    if (output_file == NULL) {
        puts("[!] Failed to allocate memory!");
        h3m_exit(&h3m);
        return 1;
    }

    // H3Complete
    snprintf(output_file, len - 1, "%s%s", argv[1], H3COMPLETE_SUFFIX);
    h3m_modembed_set_target(h3m, H3M_MODEMBED_TARGET_COMPLETE);
    if (0 != h3m_write(h3m, output_file)) {
        printf("[!] Failed to write %s!", output_file);
        free(output_file);
        h3m_exit(&h3m);
        return 1;
    }
    printf("[+] Embedded %s into %s\n", argv[2], output_file);

    // HD Mod
    // Note same len is used here
    snprintf(output_file, len - 1, "%s%s", argv[1], HDMOD_SUFFIX);
    h3m_modembed_set_target(h3m, H3M_MODEMBED_TARGET_HDMOD);
    if (0 != h3m_write(h3m, output_file)) {
        printf("[!] Failed to write %s!", output_file);
        free(output_file);
        h3m_exit(&h3m);
        return 1;
    }
    printf("[+] Embedded %s into %s\n", argv[2], output_file);

    free(output_file);
    h3m_exit(&h3m);

    return 0;
}
コード例 #3
0
ファイル: main.c プロジェクト: bfosterjr/portfwd
int main(int argc, char** argv)
{
    int     c           = 0;
    char*   lport       = NULL;
    char*   rport       = NULL;
    char*   raddress    = NULL;
    ULONG   xorKey      = 0;

    while ((c = getopt(argc, argv, "l:a:p:t")) != EOF)
    {
        switch (c)
        {
        case ('l') :
            lport = optarg;
            break;
        case ('a') :
            raddress = optarg;
            break;
        case ('p') :
            rport = optarg;
            break;
        case('t') :
            xorKey = DEFAULT_XOR;
            break;
        default:
            break;
        }
    }

    if (NULL == rport || 
        NULL == lport || 
        NULL == raddress)
    {
        _print_usage();
    }
    else
    {
        portfwd(lport, raddress, rport, xorKey);
    }
}
コード例 #4
0
ファイル: sasearch.c プロジェクト: cpockrandt/pr_dict_cmp
int
main(int argc, const char *argv[]) {
    int i;
    searchoption_t option;

    if(argc <= 1) {
        _print_usage(argv[0], EXIT_SUCCESS);
    }

    option.maxcount = -1;
    option.fname = NULL;
    option.flags = 0;
    option.func = _print_suffixes;
    option.alen = option.blen = 10;

    for(i = 1; i < argc; ++i) {
        if(argv[i][0] != '-') {
            break;
        }

        if((strcmp(argv[i], "-h") == 0) || (strcmp(argv[i], "--help") == 0)) {
            _print_usage(argv[0], EXIT_SUCCESS);
        }
        if((strcmp(argv[i], "-v") == 0) || (strcmp(argv[i], "--version") == 0)) {
            _print_version_and_license(argv[0], EXIT_SUCCESS);
        }

        if(strcmp(argv[i],"-m")==0) {
            if((i + 1) == argc) {
                fprintf(stderr,"%s: option requires an argument -- %s\n", argv[0], argv[i]);
                _print_tryhelp(argv[0], EXIT_FAILURE);
            }
            option.maxcount = atoi(argv[++i]);
        } else if(strcmp(argv[i],"-b")==0) {
            option.flags |= SA_PRINT_OFFSET;
        } else if(strcmp(argv[i],"-H")==0) {
            option.flags |= SA_PRINT_FILENAME;
        } else if(strcmp(argv[i],"-c")==0) {
            option.func = _onlyprint_count;
        } else if(strcmp(argv[i],"-S")==0) {
            option.flags |= SA_SORT_LEXICOGRAPHICALORDER;
        } else if(strcmp(argv[i],"-B")==0) {
            if((i + 1) == argc) {
                fprintf(stderr,"%s: option requires an argument -- %s\n", argv[0], argv[i]);
                _print_tryhelp(argv[0], EXIT_FAILURE);
            }
            option.blen = atoi(argv[++i]);
        } else if(strcmp(argv[i],"-A")==0) {
            if((i + 1) == argc) {
                fprintf(stderr,"%s: option requires an argument -- %s\n", argv[0], argv[i]);
                _print_tryhelp(argv[0], EXIT_FAILURE);
            }
            option.alen = atoi(argv[++i]);
        } else if(strcmp(argv[i],"-C")==0) {
            if((i + 1) == argc) {
                fprintf(stderr,"%s: option requires an argument -- %s\n", argv[0], argv[i]);
                _print_tryhelp(argv[0], EXIT_FAILURE);
            }
            option.alen = option.blen = atoi(argv[++i]);

        } else if(strcmp(argv[i],"--hex")==0) {
            option.flags |= SA_HEX_MODE;

        } else {
            fprintf(stderr,"%s: invalid option -- %s\n", argv[0], argv[i]);
            _print_tryhelp(argv[0], EXIT_FAILURE);
        }
    }

    if(i == argc) {
        return 0;
    }

    sauchar_t *P = (sauchar_t *)argv[i];
    saidx_t Psize = (saidx_t)strlen(argv[i]);

    if(option.flags & SA_HEX_MODE) {
        sauchar_t *newP = malloc(Psize / 2 * sizeof(sauchar_t));
        saidx_t j, k;
        unsigned char c, t;
        if(newP == NULL) {
            fprintf(stderr, "%s: Cannot allocate memory.\n", argv[0]);
            exit(EXIT_FAILURE);
        }
        for(j = 0, k = 0, c = 0; j < Psize; ++j) {
            if((('0' <= P[j]) && (P[j] <= '9')) || (('a' <= P[j]) && (P[j] <= 'f'))) {
                t = (('0' <= P[j]) && (P[j] <= '9')) ? P[j] - '0' : (P[j] - 'a' + 10);
                c = (c << 4) | t;
                if(k & 1) {
                    newP[k / 2] = c;
                }
                k += 1;
            }
        }
        Psize = k / 2;
        P = newP;
    }

    for(i += 1; (i + 1) < argc; i += 2) {
        FILE *fp;
        sauchar_t *T;
        saidx_t *SA;
        saidx_t size;

#if HAVE_SYS_STAT_H
        struct stat s;
        if(stat(argv[i], &s) != 0) {
            fprintf(stderr, "%s: Cannot stat file `%s': ", argv[0], argv[i]);
            perror(NULL);
            exit(EXIT_FAILURE);
        }
        size = s.st_size;
#endif

        option.fname = argv[i];
        /* Open a file for reading. */
        if((fp = fopen(argv[i], "rb")) == NULL) {
            fprintf(stderr, "%s: Cannot open file `%s': ", argv[0], argv[i]);
            perror(NULL);
            exit(EXIT_FAILURE);
        }
#if !HAVE_SYS_STAT_H
        if(fseek(fp, 0, SEEK_END) != 0) {
            fprintf(stderr, "%s: Cannot fseek on `%s': ", argv[0], argv[i]);
            perror(NULL);
            exit(EXIT_FAILURE);
        }
        if((size = ftell(fp)) == -1) {
            fprintf(stderr, "%s: Cannot ftell on `%s': ", argv[0], argv[i]);
            perror(NULL);
            exit(EXIT_FAILURE);
        }
        rewind(fp);
#endif

        /* Allocate n+4(n+1) bytes of memory. */
        if(((T = malloc(size * sizeof(sauchar_t))) == NULL) ||
                ((SA = malloc((size + 1) * sizeof(saidx_t))) == NULL)) {
            fprintf(stderr, "%s: Cannot allocate memory.\n", argv[0]);
            exit(EXIT_FAILURE);
        }

        /* Read n * sizeof(sauchar_t) bytes of data. */
        if(fread(T, sizeof(sauchar_t), size, fp) != size) {
            fprintf(stderr, "%s: %s `%s': ",
                    argv[0],
                    (ferror(fp) || !feof(fp)) ? "Cannot read from" : "Unexpected EOF in",
                    argv[i]);
            perror(NULL);
            exit(EXIT_FAILURE);
        }
        fclose(fp);

        /* Open a SA file for reading. */
        if((fp = fopen(argv[i + 1], "rb")) == NULL) {
            fprintf(stderr, "%s: Cannot open file `%s': ", argv[0], argv[i + 1]);
            perror(NULL);
            exit(EXIT_FAILURE);
        }
        /* Read (n + 1) * sizeof(saidx_t) bytes of data. */
        if(fread(SA, sizeof(saidx_t), size + 1, fp) != (size + 1)) {
            fprintf(stderr, "%s: %s `%s': ",
                    argv[0],
                    (ferror(fp) || !feof(fp)) ? "Cannot read from" : "Unexpected EOF in",
                    argv[i + 1]);
            perror(NULL);
            exit(EXIT_FAILURE);
        }
        fclose(fp);

        _search_file(T, size, P, Psize, SA, size + 1, &option);

        free(T);
        free(SA);
    }

    if(option.flags & SA_HEX_MODE) {
        free(P);
    }

    return 0;
}
コード例 #5
0
ファイル: main.c プロジェクト: IlyaLab/kramtools
int main( int argc, char *argv[] ) {

	int exit_status = EXIT_SUCCESS;

	const char *i_file = NULL;
	const char *o_file = NULL;
	FILE *fp           = NULL;

	if( argc < 2 ) { // absolute minimum args: <executable name> <input matrix>
		_print_usage( argv[0], stdout, USAGE_SHORT );
		exit( EXIT_SUCCESS );
	}

	_jit_initialization();

	do {

		static const char *CHAR_OPTIONS
#ifdef HAVE_LUA
			= "s:hrt:N:C:P:n:x:c:DM:p:f:q:v:?X";
#else
			= "hrt:N:C:P:n:x:DM:p:f:q:v:?X";
#endif

		static struct option LONG_OPTIONS[] = {
#ifdef HAVE_LUA
			{"script",        required_argument,  0,'s'},
#endif
			{"no-header",     no_argument,        0,'h'},
			{"no-row-labels", no_argument,        0,'r'},
			{"type-parser",   required_argument,  0,'t'},
			{"na-regex",      required_argument,  0,'N'},

			{"crossprod",     required_argument,  0,'C'},
			{"pair",          required_argument,  0,'P'},
			{"by-name",       required_argument,  0,'n'},
			{"by-index",      required_argument,  0,'x'},
#ifdef HAVE_LUA
			{"coroutine",     required_argument,  0,'c'},
#endif
			{"dry-run",       no_argument,        0,'D'},

			{"min-ct-cell",   required_argument,  0, 256 }, // no short equivalents
			{"min-mx-cell",   required_argument,  0, 257 }, // no short equivalents
			{"min-samples",   required_argument,  0,'M'},

			{"p-value",       required_argument,  0,'p'},
			{"format",        required_argument,  0,'f'},
			{"fdr",           required_argument,  0,'q'},
			{"verbosity",     required_argument,  0,'v'},
#ifdef _DEBUG
			{"debug",         required_argument,  0, 258 }, // no short equivalents
#endif
			{"help",          no_argument,        0,'?'},
			{ NULL,           0,                  0, 0 }
		};

		int arg_index = 0;
		const int c
			= getopt_long( argc, argv, CHAR_OPTIONS, LONG_OPTIONS, &arg_index );

		switch (c) {

		case 's': // script
			opt_script      = optarg;
			break;
		case 'h': // no-header
			opt_header      = false;
			break;
		case 'r': // no-row-labels
			opt_row_labels  = false;
			break;
		case 't': // type-parser
			opt_type_parser = optarg;
			break;
		case 'N': // na-regex
			opt_na_regex    = optarg;
			break;
		case 'C': // cross-product of matrices
			opt_preproc_matrix = optarg;
			break;
		case 'P': // pair
			opt_single_pair = optarg;
			break;
		case 'n': // by-name
			opt_pairlist_source = optarg;
			opt_by_name         = true;
			break;
		case 'x': // by-index
			opt_pairlist_source = optarg;
			opt_by_name         = false;
			break;
		case 'c': // coroutine
			opt_coroutine       = optarg;
			break;
		case 'D': // dry-run
			opt_dry_run         = true;
			break;

		////////////////////////////////////////////////////////////////////
		case 256: // ...because I haven't defined a short form for this
			arg_min_cell_count = atoi( optarg );
			break;

		case 257: // ...because I haven't defined a short form for this
			arg_min_mixb_count = atoi( optarg );
			break;

		case 'M':
			arg_min_sample_count = atoi( optarg );
			if( arg_min_sample_count < 2 ) {
				warnx( "Seriously...%d samples is acceptable?\n"
					"I don't think so... ;)\n",
					arg_min_sample_count );
				exit( EXIT_FAILURE );
			}
			break;
		////////////////////////////////////////////////////////////////////

		case 'p':
			opt_p_value = atof( optarg );
			if( ! ( 0 < opt_p_value ) ) {
				warnx( "specified p-value %.3f will preclude all output.\n",
					opt_p_value );
				abort();
			} else
			if( ! ( opt_p_value < 1.0 ) ) {
				warnx( "p-value %.3f will filter nothing.\n"
					"\tIs this really what you want?\n",
					opt_p_value );
			}
			break;

		case 'J': // JSON format
		case 'f': // tabular format
			// Check for magic-value strings first
			if( strcmp( MAGIC_FORMAT_ID_STD, optarg ) == 0 )
				_emit = format_standard;
			else
			if( strcmp( MAGIC_FORMAT_ID_TCGA, optarg ) == 0 )
				_emit = format_tcga;
			else {
				const char *specifier
					= emit_config( optarg, c=='J' ? FORMAT_JSON : FORMAT_TABULAR );
				if( specifier ) {
					errx( -1, "invalid specifier \"%s\"", specifier );
				}
				_emit = emit_exec;
			}
			break;

		case 'q':
			arg_q_value = atof( optarg );
			_analyze = _fdr_cache;
			break;

		case 'v': // verbosity
			opt_verbosity = atoi( optarg );
			break;

		case '?': // help
			_print_usage( argv[0], stdout, USAGE_SHORT );
			exit( EXIT_SUCCESS );
			break;

		case 'X': // help
			_print_usage( argv[0], stdout, USAGE_LONG );
			exit( EXIT_SUCCESS );
			break;

#ifdef _DEBUG
		case 258:
			if( strchr( optarg, 'X' ) != NULL ) {
				// Turn OFF all filtering to turn on "exhaustive"
				// output mode.
				opt_status_mask = 0;
				opt_p_value     = 1.0;
			}
			dbg_silent     = strchr( optarg, 'S' ) != NULL;
			break;
#endif
		case -1: // ...signals no more options.
			break;
		default:
			printf ("error: unknown option: %c\n", c );
			exit( EXIT_FAILURE );
		}
		if( -1 == c ) break;

	} while( true );
コード例 #6
0
ファイル: main.c プロジェクト: Abioy/ibus
int
main (int argc, char **argv)
{
    gint option_index = 0;
    gint c;

    gtk_init (&argc, &argv);
    XSetErrorHandler (_xerror_handler);

    while (1) {
        static struct option long_options [] = {
            { "debug", 1, 0, 0},
            { "server-name", 1, 0, 0},
            { "locale", 1, 0, 0},
            { "locale-append", 1, 0, 0},
            { "help", 0, 0, 0},
            { "kill-daemon", 0, 0, 0},
            { 0, 0, 0, 0},
        };

        c = getopt_long (argc, argv, "v:n:l:k:a",
            long_options, &option_index);

        if (c == -1) break;

        switch (c) {
        case 0:
            if (g_strcmp0 (long_options[option_index].name, "debug") == 0) {
                g_debug_level = atoi (optarg);
            }
            else if (g_strcmp0 (long_options[option_index].name, "server-name") == 0) {
                g_free (_server_name);
                _server_name = g_strdup (optarg);
            }
            else if (g_strcmp0 (long_options[option_index].name, "locale") == 0) {
                g_free (_locale);
                _locale = g_strdup (optarg);
            }
            else if (g_strcmp0 (long_options[option_index].name, "locale-append") == 0) {
                gchar *tmp = g_strdup_printf ("%s,%s",
                                _locale != NULL ? _locale : LOCALES_STRING, optarg);
                g_free (_locale);
                _locale = tmp;
            }
            else if (g_strcmp0 (long_options[option_index].name, "help") == 0) {
                _print_usage (stdout, argv[0]);
                exit (EXIT_SUCCESS);
            }
            else if (g_strcmp0 (long_options[option_index].name, "kill-daemon") == 0) {
                _kill_daemon = TRUE;
            }
            break;
        case 'v':
            g_debug_level = atoi (optarg);
            break;
        case 'n':
            g_free (_server_name);
            _server_name = g_strdup (optarg);
            break;
        case 'l':
            g_free (_locale);
            _locale = g_strdup (optarg);
            break;
        case 'a': {
                gchar *tmp = g_strdup_printf ("%s,%s",
                                _locale != NULL ? _locale : LOCALES_STRING, optarg);
                g_free (_locale);
                _locale = tmp;
            }
            break;
        case 'k':
            _kill_daemon = TRUE;
            break;
        case '?':
        default:
            _print_usage (stderr, argv[0]);
            exit (EXIT_FAILURE);
        }
    }

    _x11_ic_table = g_hash_table_new (g_direct_hash, g_direct_equal);
    _connections = g_hash_table_new (g_direct_hash, g_direct_equal);

    signal (SIGINT, _sighandler);
    signal (SIGTERM, _sighandler);

    if (_kill_daemon)
        g_atexit (_atexit_cb);

    _xim_init_IMdkit ();
    gtk_main();

    exit (EXIT_SUCCESS);
}
コード例 #7
0
int main(int argc, char **argv)
{
    FILE *stdlog = NULL;
    bool borderless = false;
    char *input_pathname = NULL;
    char *output_pathname = NULL;
    int  debug = DBG_ALL;
    int option;
    int option_index;
    int render_flags = 0;
    int printable_width = -1;
    int printable_height = -1;
    int rotation = -1;
    int inkjet = 1;
    int resolution = 300;
    int page_backside = 0;
    int stripe_height = STRIPE_HEIGHT;
    int concurrent_stripes = (BUFFERED_ROWS / STRIPE_HEIGHT);
    DF_duplex_t duplex = DF_DUPLEX_MODE_NONE;
    DF_media_size_t media_size = DF_MEDIA_SIZE_UNKNOWN;
    output_format_t output_format = OUTPUT_PPM;
    int testResult = ERROR;
    double extra_margin_left, extra_margin_right, extra_margin_top, extra_margin_bottom;
    int padding_options = PAD_NONE;

    extra_margin_left = extra_margin_right = extra_margin_top = extra_margin_bottom = 0.0f;

    const char *logfilename = NULL;

    FILE *imgfile    = NULL;
    FILE *outputfile = NULL;

    bool monochrome = false;

#ifndef EXCLUDE_PCLM
    bool pclm_test_mode = false;
    uint8 *pclm_output_buffer = NULL;
    void *pclmgen_obj= NULL;

    int outBuffSize = 0;

    PCLmPageSetup mypage;
    PCLmPageSetup  *page_info = &mypage;
    memset(page_info, 0, sizeof(PCLmPageSetup));
#endif /* EXCLUDE_PCLM */

   //Add pwg definitions
#ifndef NO_CUPS
    cups_raster_t *ras_out = NULL; /* Raster stream */
    cups_page_header2_t header_pwg; /* Page header */
#endif /* NO_CUPS */
    while ( (option = getopt_long(argc, argv, "i:o:d:l:w:h:f:s:c:m:r:2:p:x:e:buz?v", 
                             long_options, &option_index)) != EOF )
    {
        switch(option)
        {
            case 'i':
                input_pathname = optarg;
                break;

            case 'o':
                output_pathname = optarg;
                break;

            case 'd':
                debug = atoi(optarg);
                break;

            case 'l':
                logfilename = optarg;
                break;

            case 'b':
                borderless = true;
                break;

            case 'f':
                render_flags = atoi(optarg);
                break;

            case 'm':
                media_size = atoi(optarg);
                break;

            case 'w':
                printable_width = atoi(optarg);
                break;

            case 'h':
                printable_height = atoi(optarg);
                break;

            case 'r':
                rotation = atoi(optarg);
                break;

            case '2':
                duplex = atoi(optarg);
                break;

            case 'z':
                inkjet = 0;
                break;

            case 'x':
                resolution = atoi(optarg);
                break;

            case 'u':
                page_backside = 1;
                break;

            case 'p':
                output_format = atoi(optarg);
                break;

            case 's':
                stripe_height = atoi(optarg);
                break;

            case 'c':
                concurrent_stripes = atoi(optarg);
                break;

            case 'e':
                padding_options = atoi(optarg) & PAD_ALL;
                break;

            case OPTION_EXTRA_MARGIN_LEFT:
                extra_margin_left = atof(optarg);
                break;

            case OPTION_EXTRA_MARGIN_RIGHT:
                extra_margin_right = atof(optarg);
                break;

            case OPTION_EXTRA_MARGIN_TOP:
                extra_margin_top = atof(optarg);
                break;
            case OPTION_EXTRA_MARGIN_BOTTOM:
                extra_margin_bottom = atof(optarg);
                break;

            case OPTION_MONOCHROME:
                monochrome = true;
                break;

            case 'v':
#ifndef EXCLUDE_PCLM
                pclm_test_mode = true;
                break;
#endif /* EXCLUDE_PCLM */

            case '?':
            default:
                _print_usage(argv[0]);
                return(0);
        }  /*  switch(option)  */
    }  /*  while */

    // logging to a file?
    if (logfilename != NULL) {
        // open the logfile
        stdlog = fopen(logfilename, "w");
    }

    // set the logging level and output
    wprint_set_debug_level(debug);
    wprint_set_stdlog(((stdlog != NULL) ? stdlog : stderr));
    {
        char buffer[4096];

		int param;
        snprintf(buffer, sizeof(buffer), "JOB PARAMETERS:");
		for(param = 1; param < argc; param++)
		{
            strncat(buffer, " ", sizeof(buffer));
            strncat(buffer, argv[param], sizeof(buffer));
		}
        ifprint((DBG_FORCE, "%s", buffer));
    }

    switch(output_format) {
#ifndef EXCLUDE_PCLM
        case OUTPUT_PDF:
            if (!pclm_test_mode) {
                padding_options = PAD_ALL;
            }
            break;
#endif /* EXCLUDE_PCLM */

#ifndef NO_CUPS
        case OUTPUT_PWG:
            break;
#endif /* NO_CUPS */

        case OUTPUT_PPM:
            break;

        default:
            ifprint((DBG_FORCE, "ERROR: output format not supported, switching to PPM"));
            output_format = OUTPUT_PPM;
            break;
    }

    do {

        /*  if input file is specified at the end of the command line 
         *  without the '-f' option, take it  
         */
        if (!input_pathname && optind < argc && argv[optind] != NULL)
        {
            // coverity[var_assign_var]
            input_pathname = argv[optind++];
        }

        if (!input_pathname)
        {
            ifprint((DBG_FORCE, "ERROR: invalid arguments"));
            _print_usage(argv[0]);
            continue;
        }

        /*  if output file is specified at the end of the command line 
         *  without the '-f' option, take it  
         */
        if (!output_pathname && optind < argc && argv[optind] != NULL)
        {
            // coverity[var_assign_var]
            output_pathname = argv[optind++];
        }

        if ((media_size != DF_MEDIA_SIZE_UNKNOWN) &&
            (printable_width <= 0) && (printable_height <= 0))
        {
            float margin_top, margin_bottom, margin_left, margin_right;
            wprint_job_params_t job_params;
            printer_capabilities_t printer_caps;

            memset(&job_params, 0, sizeof(wprint_job_params_t));
            memset(&printer_caps, 0, sizeof(printer_capabilities_t));
            printer_caps.canDuplex = 1;
            printer_caps.canPrintBorderless = 1;
            printer_caps.inkjet = inkjet;

            job_params.media_size = media_size;
            job_params.pixel_units = resolution;
            job_params.duplex = duplex,
            job_params.borderless = borderless;

            switch(output_format) {
#ifndef EXCLUDE_PCLM
                case OUTPUT_PDF:
                    job_params.pcl_type = PCLm;
                    break;
#endif /* EXCLUDE_PCLM */

#ifndef NO_CUPS
                case OUTPUT_PWG:
                    job_params.pcl_type = PCLPWG;
                    break;
#endif /* NO_CUPS */

                default:
                    job_params.pcl_type = PCLNONE;
                    break;
            }

            printable_area_get_default_margins(&job_params, &printer_caps, &margin_top, &margin_left, &margin_right, &margin_bottom);
            printable_area_get(&job_params, margin_top, margin_left, margin_right, margin_bottom);

            printable_width  = job_params.printable_area_width;
            printable_height = job_params.printable_area_height;

           // mypage.mediaWidthInPixels = printable_width;
            //mypage.mediaHeightInPixels = printable_height;

#ifndef EXCLUDE_PCLM
             if(margin_left < 0.0f || margin_top < 0.0f)
             {
                 mypage.mediaWidthOffset=0.0f;
                 mypage.mediaHeightOffset=0.0f;
             }
             else
             {
                 mypage.mediaWidthOffset=margin_left;
                 mypage.mediaHeightOffset=margin_top;
             }
             mypage.pageOrigin=top_left;	// REVISIT
             mypage.dstColorSpaceSpefication=deviceRGB;
#endif /* EXCLUDE_PCLM */
        }

#ifndef EXCLUDE_PCLM
        mypage.stripHeight=stripe_height;

        if(resolution==300)
        {
            mypage.destinationResolution=res300;
        }
        else if(resolution==600)
        {
            mypage.destinationResolution=res600;
        }
        else if(resolution==1200)
        {
            mypage.destinationResolution=res1200;
        }

        mypage.duplexDisposition=simplex;
        mypage.mirrorBackside=false;
#endif /* EXCLUDE_PCLM */

        if ((printable_width <= 0) || (printable_height <= 0)) {
            ifprint((DBG_FORCE, "ERROR: missing argumetns for dimensions"));
            _print_usage(argv[0]);
            continue;
        }

        imgfile = fopen(input_pathname, "r");
        if (imgfile == NULL) {
            ifprint((DBG_FORCE, "unable to open input file"));
            continue;
        }

        testResult = OK;

        outputfile = NULL;
        if (output_pathname != NULL) {
            outputfile = fopen(output_pathname, "w");
        } else {
            ifprint((DBG_FORCE, "output file not provided"));
        }

        wprint_image_info_t image_info;

        wprint_image_setup(&image_info, MIME_TYPE_HPIMAGE, &_wprint_ifc);
        wprint_image_init(&image_info);
    
        /*  get the image_info of the input file of specified MIME type  */
        if ( wprint_image_get_info(imgfile, &image_info) == OK )
        {
            if (rotation < 0) {
                rotation = ROT_0;
                if ((render_flags & RENDER_FLAG_PORTRAIT_MODE) != 0) {
                    ifprint((DBG_LOG, "_print_page(): portrait mode"));
                    rotation = ROT_0;
                } else if ((render_flags & RENDER_FLAG_LANDSCAPE_MODE) != 0) {
                    ifprint((DBG_LOG, "_print_page(): landscape mode"));
                    rotation = ROT_90;
                } else if (wprint_image_is_landscape(&image_info) &&
                    ((render_flags & RENDER_FLAG_AUTO_ROTATE) != 0)) {
                    ifprint((DBG_LOG, "_print_page(): auto mode"));
                    rotation = ROT_90;
                }
                if ((duplex == DF_DUPLEX_MODE_BOOK) &&
                    page_backside &&
                    ((render_flags & RENDER_FLAG_ROTATE_BACK_PAGE) != 0) &&
                    ((render_flags & RENDER_FLAG_BACK_PAGE_PREROTATED) == 0))
                    rotation = ((rotation == ROT_0) ? ROT_180 : ROT_270);
            }
        }
        else {
            ifprint((DBG_FORCE, "unable to process image"));
        }

        wprint_image_set_output_properties(&image_info,
                                           rotation,
                                           printable_width,
                                           printable_height,
                                           floor(resolution * extra_margin_top),
                                           floor(resolution * extra_margin_left),
                                           floor(resolution * extra_margin_right),
                                           floor(resolution * extra_margin_bottom),
                                           render_flags,
                                           stripe_height,
                                           concurrent_stripes,
                                           padding_options);

        int buff_size = wprint_image_get_output_buff_size(&image_info);

        unsigned char * buff = (unsigned char *)malloc(buff_size);
        memset(buff, 0xff, buff_size);

        int rows_left, num_rows;
        int output_width = wprint_image_get_width(&image_info);
        num_rows = rows_left = wprint_image_get_height(&image_info);
        int bytes_per_row = BYTES_PER_PIXEL(output_width);

        // process job start
        switch(output_format)
        {
#ifndef EXCLUDE_PCLM
            case OUTPUT_PDF: {
                pclmgen_obj= (void*)CreatePCLmGen();
                outBuffSize = 0;
                PCLmStartJob(pclmgen_obj, (void**)&pclm_output_buffer, &outBuffSize, pclm_test_mode);
                if (outputfile != NULL) {
                    fwrite((char *)pclm_output_buffer, 1, outBuffSize, outputfile);
                }
                break;
            }
#endif /* EXCLUDE_PCLM */

#ifndef NO_CUPS
            case OUTPUT_PWG: {
                ras_out = cupsRasterOpen(fileno(outputfile), CUPS_RASTER_WRITE_PWG);
                break;
            }
#endif /* NO_CUPS */

            default: {
                break;
            }

        }

        // write start page information
        switch(output_format)
        {
#ifndef EXCLUDE_PCLM
            case OUTPUT_PDF: {
                mypage.SourceWidthPixels    = output_width;
                mypage.SourceHeightPixels  = num_rows;
                if (media_size != DF_MEDIA_SIZE_UNKNOWN) {
                    _get_pclm_media_size_name(media_size, (char*)mypage.mediaSizeName);
                    PCLmGetMediaDimensions(pclmgen_obj, mypage.mediaSizeName, &mypage );
                } else {
                    strcpy((char*)mypage.mediaSizeName, "CUSTOM");
				    mypage.mediaWidth      = (((float)printable_width * STANDARD_SCALE_FOR_PDF)/(float)resolution);
				    mypage.mediaHeight     = (((float)printable_height * STANDARD_SCALE_FOR_PDF)/(float)resolution);
				    mypage.mediaWidthInPixels   = printable_width;
				    mypage.mediaHeightInPixels   = printable_height;
                }
                float   standard_scale =(float)resolution/(float)72;
                page_info->sourceHeight = (float)num_rows/standard_scale;
	            page_info->sourceWidth = (float)output_width/standard_scale;
	            page_info->colorContent=color_content;
                page_info->srcColorSpaceSpefication=deviceRGB;
                page_info->compTypeRequested=compressDCT;
                outBuffSize = 0;
                PCLmStartPage(pclmgen_obj, page_info, (void**)&pclm_output_buffer, &outBuffSize);
                if (outputfile != NULL) {
                    fwrite((char *)pclm_output_buffer, 1, outBuffSize, outputfile);
                }
                break;
            }
#endif /* EXCLUDE_PCLM */

#ifndef NO_CUPS
            case OUTPUT_PWG: {
                _write_header_pwg(ras_out, resolution, image_info, &header_pwg, monochrome);

                /*
                  * Output the pages...
                */

                ifprint((DBG_LOG, "cupsWidth = %d", header_pwg.cupsWidth));
                ifprint((DBG_LOG, "cupsHeight = %d", header_pwg.cupsHeight));
                ifprint((DBG_LOG, "cupsBitsPerColor = %d", header_pwg.cupsBitsPerColor));
                ifprint((DBG_LOG, "cupsBitsPerPixel = %d", header_pwg.cupsBitsPerPixel));
                ifprint((DBG_LOG, "cupsBytesPerLine = %d", header_pwg.cupsBytesPerLine));
                ifprint((DBG_LOG, "cupsColorOrder = %d", header_pwg.cupsColorOrder));
                ifprint((DBG_LOG, "cupsColorSpace = %d", header_pwg.cupsColorSpace));
                break;
            }
#endif /* NO_CUPS */

            default: {
                _write_header(outputfile, output_width, num_rows, monochrome);
                break;
            }
        }

        int height, nbytes;
        int image_row = 0;
        int actual_rows = 0;

        while(rows_left > 0) {
            height = MIN(rows_left, stripe_height);
        
            nbytes = wprint_image_decode_stripe(&image_info,
                                            image_row,
                                            &height,
                                            buff);

            if (nbytes > 0) {
                int rows_returned = (nbytes / bytes_per_row);
                actual_rows += rows_returned;
                if (height != rows_returned) {
                    ifprint((DBG_LOG, "LOG: mismatch in reported bytes & height: %d vs %d", height, rows_returned));
                }
                if (monochrome) {
                    int readIndex, writeIndex;
                    for(readIndex = writeIndex = 0; readIndex < nbytes; readIndex += BYTES_PER_PIXEL(1)) {
                        unsigned char gray = SP_GRAY(buff[readIndex + 0], buff[readIndex + 1], buff[readIndex + 2]);
                        buff[writeIndex++] = gray;
                        if (output_format == OUTPUT_PDF) {
                            buff[writeIndex++] = gray;
                            buff[writeIndex++] = gray;
                        }
                    }
                    nbytes = writeIndex;
                }

                // write the data
                switch(output_format)
                {
#ifndef EXCLUDE_PCLM
                    case OUTPUT_PDF: {
                        outBuffSize= 0;
                        PCLmEncapsulate(pclmgen_obj, buff, bytes_per_row, rows_returned, (void**)&pclm_output_buffer, &outBuffSize);
                        if (outputfile != NULL) {
                            fwrite((char *)pclm_output_buffer, 1, outBuffSize, outputfile);
                        }
                        break;
                    }
#endif /* EXCLUDE_PCLM */

#ifndef NO_CUPS
                    case OUTPUT_PWG: {
                        if (ras_out != NULL) {
                            cupsRasterWritePixels(ras_out, buff, nbytes);
                        }
                        break;
                    }
#endif /* NO_CUPS */
                    
                    default: {
                        if (outputfile != NULL) {
                            fwrite(buff, 1, nbytes, outputfile);
                        }
                    }
                }

                image_row += height;
                rows_left -= height;
            } else {
                if (nbytes < 0) {
                    ifprint((DBG_ERROR, "ERROR: file appears to be corrupted"));
                } else {
                    ifprint((DBG_ERROR, "LOG: data end with request image_row: %d for %d rows", image_row, MIN(rows_left, stripe_height)));
                }
                break;
            }
        }

        if (num_rows != actual_rows) {
            ifprint((DBG_ERROR, "ERROR: actual image rows: %d", actual_rows));
        }

        // end of page processing
        switch(output_format) {
#ifndef EXCLUDE_PCLM
                case OUTPUT_PDF: {
                    outBuffSize = 0;
                    PCLmEndPage(pclmgen_obj, (void**)&pclm_output_buffer, &outBuffSize);
                    if (outputfile != NULL) {
                        fwrite((char *)pclm_output_buffer, 1, outBuffSize, outputfile);
                    }
                    break;
                }
#endif /* EXCLUDE_PCLM */

#ifndef NO_CUPS
                case OUTPUT_PWG: {
                    break;
                }
#endif /* NO_CUPS */

                default: {
                    if (num_rows != actual_rows) {
                        _write_header(outputfile, wprint_image_get_width(&image_info), actual_rows, monochrome);
                        break;
                    }
                    break;
                }
        }

        // end of job processing
        switch(output_format) {
#ifndef EXCLUDE_PCLM
            case OUTPUT_PDF: {
                outBuffSize = 0;
                PCLmEndJob(pclmgen_obj, (void**)&pclm_output_buffer, &outBuffSize);
                if (outputfile != NULL) {
                    fwrite((char *)pclm_output_buffer, 1, outBuffSize, outputfile);
                }

                PCLmFreeBuffer(pclmgen_obj, pclm_output_buffer);
                DestroyPCLmGen(pclmgen_obj);
                break;
            }
#endif /* EXCLUDE_PCLM */

#ifndef NO_CUPS
            case OUTPUT_PWG: {
                break;
            }
#endif /* NO_CUPS */

            default: {
                break;
            }
        }

        wprint_image_cleanup(&image_info);

        if (buff != NULL) {
            free(buff);
        }

    } while(0);

    // close the imagefile
    if (imgfile != NULL) {
        fclose(imgfile);
    }

    // close the output file
    if (outputfile != NULL) {
        fclose(outputfile);
    }

    //if we use a res stream close it
#ifndef NO_CUPS
    if(ras_out != NULL){
        cupsRasterClose(ras_out);
    }
#endif /* NO_CUPS */

    // close the logfile
    if (stdlog != NULL) {
        fclose(stdlog);
    }

    return(testResult);
}  /* main */
コード例 #8
0
int main(int argc, char **argv)
{
	char product[32] = {0};
	char version[32] = {0};
	static config_post_process_handle_t *hd=NULL;
	int i, ret = 0;
	struct stat st;
	int op_flag=0;
	int monitor_per_sec=0;

#ifdef __DISABLE_DEBUG_OUTPUT__
	freopen("/dev/null", "a", stdout);
	freopen("/dev/null", "a", stderr);
#endif

	if(argc <= 1){
		_print_usage(argv[0]);
		goto out;
	}
	for(i=1;i<argc;i++){
		if(!strcmp(argv[i], "-e") || !strcmp(argv[i], "--eraseflash")){
			/* load the config */
			op_flag |= CONFIG_TOOL_OP_ERASE_FLASH;
		}
		if(!strcmp(argv[i], "-l") || !strcmp(argv[i], "--load")){
			/* load the config */
			op_flag |= CONFIG_TOOL_OP_LOAD;
		}
		if(!strcmp(argv[i], "-s") || !strcmp(argv[i], "--save") || !strcmp(argv[i], "-r") || !strcmp(argv[i], "--reset")){
			if(!strcmp(argv[i], "-r") || !strcmp(argv[i], "--reset"))
				securesoho_factory_default();
			/* save the config */
			op_flag |= CONFIG_TOOL_OP_SAVE;
			/* erase the flash */
			if(op_flag&CONFIG_TOOL_OP_ERASE_FLASH) {
				flash_op_t *p_flash_op = NULL;
				p_flash_op = create_flash_op();	
				flash_op_erase(p_flash_op, TARGET_FILE, NULL);
#ifdef CONF_CONFIG_MTD_PARTITION_BACKUP
				flash_op_erase(p_flash_op, TARGET_FILE2, NULL);
#endif
				destroy_flash_op(&p_flash_op);
			}
			/* save config */
			securesoho_get_curversion(version);
			mkconfig_translate_config_dir_to_file(SOURCE_DIR, TARGET_FILE, CONF_PRODUCT, version);
#ifdef CONF_CONFIG_MTD_PARTITION_BACKUP
                        mkconfig_translate_config_dir_to_file(SOURCE_DIR, TARGET_FILE2, CONF_PRODUCT, version);
#endif
		}
		if(!strcmp(argv[i], "-m") || !strcmp(argv[i], "--monitor")){
			int err=0;
			/* monitor the config */
			op_flag |= CONFIG_TOOL_OP_MONITOR;
			i++;
			if(i<argc){
				monitor_per_sec = atoi(argv[i]);
				if(monitor_per_sec == 0){
					err = 1;
				}
			}else{
				err = 2;
			}
			if(err){
				printf("ERR:-m %d\n", err);
				_print_usage(argv[0]);
				exit(0);
			}
		}
		if(!strcmp(argv[i], "-c") || !strcmp(argv[i], "--change")){
			int err=1;
			char *conf=NULL;
			char *str=NULL, *p;
			i++;
			while(i<argc){
				str = strdup(argv[i]);
				p = strchr(str, '=');
				if(NULL==p){
					if (conf) free(conf);
					conf = strdup(str);
					i++;
				}else{
					*p = '\0';
					if (NULL == conf){
						printf("config saved val:key =>(%s,%s)\n", str, p+1);
						securesoho_string_set(str,  p+1);
					}else{
						printf("config saved val:key [%s]=>(%s,%s)\n", conf, str, p+1);
						bs_config_string_set(conf, str, p+1);
					}
					err=0;
					break;
				}
				free(str);
			}
			if(err){
				printf("ERR:-c %d\n", err);
				_print_usage(argv[0]);
			}
			exit(0);
		}
		if(!strcmp(argv[i], "-t") || !strcmp(argv[i], "--savedir")){
			int err=0;
			char *str, *p;

			op_flag |= CONFIG_TOOL_OP_SAVEDIR;
			i++;
			if(i<argc){
				str = strdup(argv[i]);
				p = strchr(str, '=');
				if(p){
					*p = '\0';
 					/* erase the flash */
					if(op_flag&CONFIG_TOOL_OP_ERASE_FLASH) {
						flash_op_t *p_flash_op = NULL;
						p_flash_op = create_flash_op();	
						flash_op_erase(p_flash_op, p+1, NULL);
						destroy_flash_op(&p_flash_op);
					}
					printf("saved dir: (src,targe)=> (%s,%s)\n", str, p+1);
					securesoho_get_curversion(version);
					mkconfig_translate_config_dir_to_file(str, p+1, CONF_PRODUCT, version);
				}else err=1;
				free(str);
			}else err=2;
			if(err){
				printf("ERR:-c %d\n", err);
				_print_usage(argv[0]);
				exit(0);
			}
		}
		if(!strcmp(argv[i], "-x") || !strcmp(argv[i], "--extract")){
			int err=0;
			char *str;

			op_flag |= CONFIG_TOOL_OP_EXTRACT;
			i++;
			if(i<argc){
				str = strdup(argv[i]);
				mkconfig_translate_file_to_config_dir(str, product, version);
			}else err=2;
			if(err){
				printf("ERR:-c %d\n", err);
				_print_usage(argv[0]);
				exit(0);
			}
		}
		if(!strcmp(argv[i], "--mac")){
			i++;
			if (i<argc){
				bs_config_string_set(CONF_DEVICE_MP_CONFIG, "CONF_DEVICE_MP_MAC", argv[i]);
				mkconfig_translate_config_dir_to_file(MP_SOURCE_DIR, CONF_MP_MTD_PARTITION, CONF_PRODUCT, version);
				return ret == 0 ? -1 : 0; 	/* -1 fail */
			}else{
				_print_usage(argv[0]);
				return -1;
			}
		}
		if(!strcmp(argv[i], "--regiondata")){
			int err=0;
			char *str, *p1, *p2;

			op_flag |= CONFIG_TOOL_OP_REGION;
			i++;
			if(i<argc){
				device_region_data data;

				securesoho_get_curversion(version);
				
				do_mkdir(MP_SOURCE_DIR);
				mkconfig_translate_file_to_config_dir(CONF_MP_MTD_PARTITION, product, version);
				
				memset(&data, 0, sizeof(device_region_data));
				if(!strcmp(argv[i], "get")) {
					ret = securesoho_get_device_region_data(&data);
					return ret == 0 ? 0 : -1;	/* -1 fail. */
				}
				if(!strcmp(argv[i], "clean")) {
					ret = securesoho_set_device_region_data(&data);
					mkconfig_translate_config_dir_to_file(MP_SOURCE_DIR, CONF_MP_MTD_PARTITION, CONF_PRODUCT, version);
					return ret == 0 ? 0 : -1; 	/* -1 fail */
				}
				if(!strcmp(argv[i], "set")) {
					i++;
					str = strdup(argv[i]);

					p1 = strchr(str, '-');
					if(!p1) {
						err=1;
						free(str);
						printf("ERR:-c %d\n", err);
						_print_usage(argv[0]);
						return -1;
					}
					p2 = strchr(p1+1, '-');
					if(p2){
						char buf[8]={0};
						strncpy(buf, str, p1-str);
						data.version = 0;
						data.tv_mode = (unsigned char) atoi(buf);
						strncpy(buf, p1+1, p2-(p1+1));
						data.region = (unsigned char) atoi(buf);
						data.location = (unsigned char) atoi(p2+1);
						securesoho_set_device_region_data(&data);
						ret = mkconfig_translate_config_dir_to_file(MP_SOURCE_DIR, CONF_MP_MTD_PARTITION, CONF_PRODUCT, version);
						return ret == 0 ? 0 : -1; 	/* -1 fail */
					}else err=1;
					free(str);
				}
			}else err=2;
			if(err){
				printf("ERR:-c %d\n", err);
				_print_usage(argv[0]);
				return -1;
			}
		}
	}
	if(!op_flag){
		_print_usage(argv[0]);
	}
	if(op_flag & CONFIG_TOOL_OP_LOAD){
		hd = get_oem_handle(CONF_PRODUCT);
		
		/* mkdir /tmp/conf directyr */
		do_mkdir(SOURCE_DIR);
		
		/* load config */
		ret = mkconfig_translate_file_to_config_dir(TARGET_FILE, product, version);
#ifdef CONF_CONFIG_MTD_PARTITION_BACKUP
		if( ret < 0){
			ret = mkconfig_translate_file_to_config_dir(TARGET_FILE2, product, version);
		}
#endif
                
		if( ret < 0){
			securesoho_factory_default();
                }else {
			if(stat(SECURESOHO_CONFIG, &st) < 0) {
				fprintf(stderr, "can not find %s, we will securesoho_factory_default().\n", SECURESOHO_CONFIG);
				securesoho_factory_default();
			}
		}
		
		config_post_process(version);
		
		if(hd)
			hd->post_process(version);
	}
	if(op_flag & CONFIG_TOOL_OP_MONITOR){
		ptr_event_object_handler evt=NULL;
		int stop_flag=0;

		evt = create_event_proxy(EVENT_PROXY_FIFO, EPCONFIGTOOL_RD_FIFO, EPCONFIGTOOL_WR_FIFO, ep_fifo_create_cb);
		if(evt==NULL){
			/* fail to create the event proxy */
			exit(0);
		}
		flash_monitor_init();
		while(1){
			int fd, elen;
			struct timeval tv;
			CONFIG_TOOL_CMD *cmd;
			fd_set rfds;

			FD_ZERO(&rfds);
			FD_SET(config_tool_cmd_fd, &rfds);

			tv.tv_sec = monitor_per_sec;
			tv.tv_usec = 0;

			fd = select(config_tool_cmd_fd+1, &rfds, NULL, NULL, &tv);
			if(fd > 0 && FD_ISSET(config_tool_cmd_fd, &rfds)){
				/* receive t the command */
				cmd = NULL;
				event_proxy_get_event(evt, (void **)&cmd, &elen);
				if(cmd){
					switch(*cmd){
					case CONFIG_TOOL_CMD_STOP:
						fprintf(stderr, "F:%s:%d, CONFIG_TOOL_CMD_STOP\n", __FUNCTION__, __LINE__);
						stop_flag = 1;
						break;
					case CONFIG_TOOL_CMD_START:
						fprintf(stderr, "F:%s:%d, CONFIG_TOOL_CMD_START\n", __FUNCTION__, __LINE__);
						stop_flag = 0;
						break;
					case CONFIG_TOOL_CMD_DEAD:
						fprintf(stderr, "F:%s:%d, CONFIG_TOOL_CMD_DEAD\n", __FUNCTION__, __LINE__);
						goto dead;
						break;
					default:
						fprintf(stderr, "F:%s:%d, CONFIG_TOOL_CMD_UNKNOWN\n", __FUNCTION__, __LINE__);
						break;
					}
					free(cmd);
				}
			}
			if(!stop_flag){
				flash_monitor_checkforwrite(0);
			}
		}
	dead:
		flash_monitor_destroy();
	}
out:
	exit(0);
	
}
コード例 #9
0
ファイル: main.c プロジェクト: kitsune-dsu/kitsune-icecast
int main(int argc, char **argv)
{
    int res, ret;
    char filename[512];
    char pbuf[1024];

    kitsune_do_automigrate(); /**DSU data */

    if (!kitsune_is_updating()) { /**DSU control */
    /* parse the '-c icecast.xml' option
    ** only, so that we can read a configfile
    */
    res = _parse_config_opts(argc, argv, filename, 512);
    if (res == 1) {
        /* startup all the modules */
        _initialize_subsystems();

        /* parse the config file */
        config_get_config();
        ret = config_initial_parse_file(filename);
        config_release_config();
        if (ret < 0) {
            memset(pbuf, '\000', sizeof(pbuf));
            snprintf(pbuf, sizeof(pbuf)-1, 
                "FATAL: error parsing config file (%s)", filename);
            _fatal_error(pbuf);
            switch (ret) {
            case CONFIG_EINSANE:
                _fatal_error("filename was null or blank");
                break;
            case CONFIG_ENOROOT:
                _fatal_error("no root element found");
                break;
            case CONFIG_EBADROOT:
                _fatal_error("root element is not <icecast>");
                break;
            default:
                _fatal_error("XML config parsing error");
                break;
            }
            _shutdown_subsystems();
            return 1;
        }
    } else if (res == -1) {
        _print_usage();
        return 1;
    }
    
    /* override config file options with commandline options */
    config_parse_cmdline(argc, argv);

    /* Bind socket, before we change userid */
    if(!_server_proc_init()) {
        _fatal_error("Server startup failed. Exiting");
        _shutdown_subsystems();
        return 1;
    }

    _ch_root_uid_setup(); /* Change user id and root if requested/possible */

    stats_initialize(); /* We have to do this later on because of threading */
    fserve_initialize(); /* This too */

#ifdef CHUID 
    /* We'll only have getuid() if we also have setuid(), it's reasonable to
     * assume */
    if(!getuid()) /* Running as root! Don't allow this */
    {
        fprintf(stderr, "ERROR: You should not run icecast2 as root\n");
        fprintf(stderr, "Use the changeowner directive in the config file\n");
        _shutdown_subsystems();
        return 1;
    }
#endif

    /* setup default signal handlers */
    sighandler_initialize();

    if (!_start_logging()) {
        _fatal_error("FATAL: Could not start logging");
        _shutdown_subsystems();
        return 1;
    }

    INFO0 (ICECAST_VERSION_STRING " server started");

    /* REM 3D Graphics */

    /* let her rip */
    global.running = ICE_RUNNING;

    /* Startup yp thread */
    yp_initialize();

    /* Do this after logging init */
    slave_initialize();
    auth_initialise ();
    } else { /**DSU control 2 */
        /* setup default signal handlers */
        sighandler_initialize();
    } /* END EKIDEN INIT BLOCK */

    _server_proc();

    INFO0("Shutting down");

    _shutdown_subsystems();

    if (pidfile)
    {
        remove (pidfile);
        free (pidfile);
    }

    return 0;
}
コード例 #10
0
ファイル: main.c プロジェクト: miksago/icecast
int main(int argc, char **argv)
{
    int res, ret;
    ice_config_t *config;
    char *pidfile = NULL;
    char filename[512];
    char pbuf[1024];

    /* parse the '-c icecast.xml' option
    ** only, so that we can read a configfile
    */
    res = _parse_config_file(argc, argv, filename, 512);
    if (res == 1) {
        /* startup all the modules */
        _initialize_subsystems();

        /* parse the config file */
        config_get_config();
        ret = config_initial_parse_file(filename);
        config_release_config();
        if (ret < 0) {
            memset(pbuf, '\000', sizeof(pbuf));
            snprintf(pbuf, sizeof(pbuf)-1, 
                "FATAL: error parsing config file (%s)", filename);
            _fatal_error(pbuf);
            switch (ret) {
            case CONFIG_EINSANE:
                _fatal_error("filename was null of blank");
                break;
            case CONFIG_ENOROOT:
                _fatal_error("no root element found");
                break;
            case CONFIG_EBADROOT:
                _fatal_error("root element is not <icecast>");
                break;
            default:
                _fatal_error("XML config parsing error");
                break;
            }
            _shutdown_subsystems();
            return 1;
        }
    } else if (res == -1) {
        _print_usage();
        return 1;
    }
    
    /* override config file options with commandline options */
    config_parse_cmdline(argc, argv);

    /* Bind socket, before we change userid */
    if(!_server_proc_init()) {
        _fatal_error("Server startup failed. Exiting");
        _shutdown_subsystems();
        return 1;
    }

    _ch_root_uid_setup(); /* Change user id and root if requested/possible */

    stats_initialize(); /* We have to do this later on because of threading */
    fserve_initialize(); /* This too */

#ifdef CHUID 
    /* We'll only have getuid() if we also have setuid(), it's reasonable to
     * assume */
    if(!getuid()) /* Running as root! Don't allow this */
    {
        fprintf(stderr, "WARNING: You should not run icecast2 as root\n");
        fprintf(stderr, "Use the changeowner directive in the config file\n");
        _shutdown_subsystems();
        return 1;
    }
#endif

    /* setup default signal handlers */
    sighandler_initialize();

    if (!_start_logging()) {
        _fatal_error("FATAL: Could not start logging");
        _shutdown_subsystems();
        return 1;
    }

    config = config_get_config_unlocked();
    /* recreate the pid file */
    if (config->pidfile)
    {
        FILE *f;
        pidfile = strdup (config->pidfile);
        if (pidfile && (f = fopen (config->pidfile, "w")) != NULL)
        {
            fprintf (f, "%d\n", getpid());
            fclose (f);
        }
    }
    /* Do this after logging init */
    slave_initialize();

    INFO0("icecast server started");

    /* REM 3D Graphics */

    /* let her rip */
    global.running = ICE_RUNNING;

#ifdef USE_YP
    /* Startup yp thread */
    yp_initialize();
#endif

    _server_proc();

    INFO0("Shutting down");

    _shutdown_subsystems();

    if (pidfile)
    {
        remove (pidfile);
        free (pidfile);
    }

    return 0;
}
コード例 #11
0
ファイル: main.c プロジェクト: niko/icecast-kh
int server_init (int argc, char *argv[])
{
    int  ret;
    char filename[512];
    char pbuf[1024];

    switch (_parse_config_opts (argc, argv, filename, 512))
    {
        case -1:
            _print_usage();
            return -1;
        default:
            /* parse the config file */
            config_get_config();
            ret = config_initial_parse_file(filename);
            config_release_config();
            if (ret < 0)
            {
                snprintf (pbuf, sizeof(pbuf), 
                        "FATAL: error parsing config file (%s)", filename);
                _fatal_error (pbuf);
                switch (ret)
                {
                    case CONFIG_EINSANE:
                        _fatal_error("filename was null or blank");
                        break;
                    case CONFIG_ENOROOT:
                        _fatal_error("no root element found");
                        break;
                    case CONFIG_EBADROOT:
                        _fatal_error("root element is not <icecast>");
                        break;
                    default:
                        _fatal_error("XML config parsing error");
                        break;
                }
                return -1;
            }
    }

    /* override config file options with commandline options */
    config_parse_cmdline(argc, argv);

    /* Bind socket, before we change userid */
    if (_server_proc_init() == 0)
    {
        _fatal_error("Server startup failed. Exiting");
        return -1;
    }
    fserve_initialize();

#ifdef CHUID 
    /* We'll only have getuid() if we also have setuid(), it's reasonable to
     * assume */
    if (getuid() == 0) /* Running as root! Don't allow this */
    {
        fprintf (stderr, "ERROR: You should not run icecast2 as root\n");
        fprintf (stderr, "Use the changeowner directive in the config file\n");
        return -1;
    }
#endif
    /* setup default signal handlers */
    sighandler_initialize();

    if (start_logging (config_get_config_unlocked()) < 0)
    {
        _fatal_error("FATAL: Could not start logging");
        return -1;
    }
    return 0;
}
コード例 #12
0
ファイル: main.c プロジェクト: Cougar/dircproxy
/* We need this */
int main(int argc, char *argv[]) {
  int optc, show_help, show_version, show_usage;
  char *local_file, *cmd_listen_port, *cmd_pid_file;
  int inetd_mode, no_daemon;

  /* Set up some globals */
  progname = argv[0];
  listen_port = x_strdup(DEFAULT_LISTEN_PORT);
  pid_file = (DEFAULT_PID_FILE ? x_strdup(DEFAULT_PID_FILE) : 0);

#ifndef DEBUG
  no_daemon = 0;
#else /* DEBUG */
  no_daemon = 1;
#endif /* DEBUG */
  local_file = cmd_listen_port = cmd_pid_file = 0;
  show_help = show_version = show_usage = inetd_mode = 0;
  while ((optc = getopt_long(argc, argv, GETOPTIONS, long_opts, NULL)) != -1) {
    switch (optc) {
      case 'h':
        show_help = 1;
        break;
      case 'v':
        show_version = 1;
        break;
      case 'D':
#ifndef DEBUG
        no_daemon = 1;
#else /* DEBUG */
        no_daemon = 0;
#endif /* DEBUG */
        break;
      case 'I':
        inetd_mode = 1;
        break;
      case 'P':
        free(cmd_listen_port);
        cmd_listen_port = x_strdup(optarg);
        break;
      case 'p':
        free(cmd_pid_file);
        cmd_pid_file = x_strdup(optarg);
        break;
      case 'f':
        free(local_file);
        local_file = x_strdup(optarg);
        break;
      default:
        show_usage = 1;
        break;
    }
  }

  if (show_usage || (optind < argc)) {
    _print_usage();
    return 1;
  }

  if (show_version) {
    _print_version();
    if (!show_help)
      return 0;
  }

  if (show_help) {
    _print_help();
    return 0;
  }

  /* If no -f was specified use the home directory */
  if (!local_file && !inetd_mode) {
    struct stat statinfo;
    struct passwd *pw;

    pw = getpwuid(geteuid());
    if (pw && pw->pw_dir) {
      local_file = x_sprintf("%s/%s", pw->pw_dir, USER_CONFIG_FILENAME);
      debug("Local config file: %s", local_file);
      if (!stat(local_file, &statinfo) && (statinfo.st_mode & 0077)) {
        fprintf(stderr, "%s: Permissions of %s must be 0700 or "
                        "more restrictive\n", progname, local_file);
        free(local_file);
        return 2;
      }
      if (cfg_read(local_file, &listen_port, &pid_file, &g)) {
        /* If the local one didn't exist, set to 0 so we open
           global one */
        free(local_file);
        local_file = 0;
      } else {
        config_file = x_strdup(local_file);
      }
    }
  } else if (local_file) {
    if (cfg_read(local_file, &listen_port, &pid_file, &g)) {
      /* This is fatal! */
      fprintf(stderr, "%s: Couldn't read configuration from %s: %s\n",
              progname, local_file, strerror(errno));
      free(local_file);
      return 2;
    } else {
      config_file = x_strdup(local_file);
    }
  }

  /* Read global config file if local one not found */
  if (!local_file) {
    char *global_file;

    /* Not fatal if it doesn't exist */
    global_file = x_sprintf("%s/%s", SYSCONFDIR, GLOBAL_CONFIG_FILENAME);
    debug("Global config file: %s", global_file);
    cfg_read(global_file, &listen_port, &pid_file, &g);
    config_file = x_strdup(global_file);
    free(global_file);
  } else {
    free(local_file);
  }

  /* Check we got some connection classes */
  if (!connclasses) {
    fprintf(stderr, "%s: No connection classes have been defined.\n", progname);
    return 2;
  }

  /* -P overrides config file */
  if (cmd_listen_port) {
    free(listen_port);
    listen_port = cmd_listen_port;
  }

  /* -p overrides pid file */
  if (cmd_pid_file) {
    free(pid_file);
    pid_file = cmd_pid_file;
  }

  /* Set signal handlers */
  signal(SIGTERM, _sig_term);
  signal(SIGINT, _sig_term);
  signal(SIGHUP, _sig_hup);
  signal(SIGCHLD, _sig_child);
#ifdef DEBUG_MEMORY
  signal(SIGUSR1, _sig_usr);
  signal(SIGUSR2, _sig_usr);
#endif /* DEBUG_MEMORY */

  /* Broken Pipe?  This means that someone disconnected while we were
     sending stuff.  Naughty! */
  signal(SIGPIPE, SIG_IGN);

  if (!inetd_mode) {
    debug("Ordinary console dodge-monkey mode");

    /* Make listening socket before we fork */
    if (ircnet_listen(listen_port)) {
      fprintf(stderr, "%s: Unable to establish listen port\n", progname);
      return 3;
    }

    /* go daemon here */
    if (!no_daemon) {
      switch (go_daemon()) {
        case -1:
          return -1;
        case 0:
          break;
        default:
          return 0;
      }
    }

  } else {
    /* running under inetd means we are backgrounded right *now* */
    in_background = 1;

    debug("Inetd SuperTed mode!");

    /* Hook STDIN into a new proxy */
    ircnet_hooksocket(STDIN_FILENO);
  }
 
  /* Open a connection to syslog if we're in the background */
  if (in_background)
    openlog(PACKAGE, LOG_PID, LOG_USER);

  if (pid_file) {
    FILE *pidfile;

    pidfile = fopen(pid_file, "w");
    if (pidfile) {
      fchmod(fileno(pidfile), 0600);
      fprintf(pidfile, "%d\n", getpid());
      fclose(pidfile);
    } else {
      syscall_fail("fopen", pid_file, 0);
    }
  }
  
  /* Main loop! */
  while (!stop_poll) {
    int ns, nt, status;
    pid_t pid;

    ircnet_expunge_proxies();
    dccnet_expunge_proxies();
    ns = net_poll();
    nt = timer_poll();

    /* Reap any children */
    while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
      debug("Reaped process %d, exit status %d", pid, status);
      
      /* Handle any DNS children */
      dns_endrequest(pid, status);
    }

    /* Reload the configuration file? */
    if (reload_config) {
      _reload_config();
      reload_config = 0;
    }

    if (!ns && !nt)
      break;
  }

  if (pid_file) {
    unlink(pid_file);
  }

  /* Free up stuff */
  ircnet_flush();
  dccnet_flush();
  dns_flush();
  timer_flush();

  /* Do a lingering close on all sockets */
  net_closeall();
  net_flush();

  /* Close down and free up memory */
  if (!inetd_mode && !no_daemon)
    closelog();
  free(listen_port);
  free(pid_file);
  free(config_file);

#ifdef DEBUG_MEMORY
  mem_report("termination");
#endif /* DEBUG_MEMORY */

  return 0;
}