static jboolean parseOptions(char *options) { TransportSpec *currentTransport = NULL; char *end; char *current; int length; char *str; char *errmsg; /* Set defaults */ gdata->assertOn = DEFAULT_ASSERT_ON; gdata->assertFatal = DEFAULT_ASSERT_FATAL; logfile = DEFAULT_LOGFILE; /* Options being NULL will end up being an error. */ if (options == NULL) { options = ""; } /* Check for "help" BEFORE we add any environmental settings */ if ((strcmp(options, "help")) == 0) { printUsage(); forceExit(0); /* Kill entire process, no core dump wanted */ } /* These buffers are never freed */ { char *envOptions; /* * Add environmentally specified options. */ envOptions = getenv("_JAVA_JDWP_OPTIONS"); if (envOptions != NULL) { options = add_to_options(options, envOptions); if ( options==NULL ) { EXIT_ERROR(AGENT_ERROR_OUT_OF_MEMORY,"options"); } } /* * Allocate a buffer for names derived from option strings. It should * never be longer than the original options string itself. * Also keep a copy of the options in gdata->options. */ length = (int)strlen(options); gdata->options = jvmtiAllocate(length + 1); if (gdata->options == NULL) { EXIT_ERROR(AGENT_ERROR_OUT_OF_MEMORY,"options"); } (void)strcpy(gdata->options, options); names = jvmtiAllocate(length + 1); if (names == NULL) { EXIT_ERROR(AGENT_ERROR_OUT_OF_MEMORY,"options"); } transports = bagCreateBag(sizeof(TransportSpec), 3); if (transports == NULL) { EXIT_ERROR(AGENT_ERROR_OUT_OF_MEMORY,"transports"); } } current = names; end = names + length; str = options; while (*str) { char buf[100]; /*LINTED*/ if (!get_tok(&str, buf, (int)sizeof(buf), '=')) { goto syntax_error; } if (strcmp(buf, "transport") == 0) { currentTransport = bagAdd(transports); /*LINTED*/ if (!get_tok(&str, current, (int)(end - current), ',')) { goto syntax_error; } currentTransport->name = current; current += strlen(current) + 1; } else if (strcmp(buf, "address") == 0) { if (currentTransport == NULL) { errmsg = "address specified without transport"; goto bad_option_with_errmsg; } /*LINTED*/ if (!get_tok(&str, current, (int)(end - current), ',')) { goto syntax_error; } currentTransport->address = current; current += strlen(current) + 1; } else if (strcmp(buf, "timeout") == 0) { if (currentTransport == NULL) { errmsg = "timeout specified without transport"; goto bad_option_with_errmsg; } /*LINTED*/ if (!get_tok(&str, current, (int)(end - current), ',')) { goto syntax_error; } currentTransport->timeout = atol(current); current += strlen(current) + 1; } else if (strcmp(buf, "launch") == 0) { /*LINTED*/ if (!get_tok(&str, current, (int)(end - current), ',')) { goto syntax_error; } launchOnInit = current; current += strlen(current) + 1; } else if (strcmp(buf, "onthrow") == 0) { /* Read class name and convert in place to a signature */ *current = 'L'; /*LINTED*/ if (!get_tok(&str, current + 1, (int)(end - current - 1), ',')) { goto syntax_error; } initOnException = current; while (*current != '\0') { if (*current == '.') { *current = '/'; } current++; } *current++ = ';'; *current++ = '\0'; } else if (strcmp(buf, "assert") == 0) { /*LINTED*/ if (!get_tok(&str, current, (int)(end - current), ',')) { goto syntax_error; } if (strcmp(current, "y") == 0) { gdata->assertOn = JNI_TRUE; gdata->assertFatal = JNI_FALSE; } else if (strcmp(current, "fatal") == 0) { gdata->assertOn = JNI_TRUE; gdata->assertFatal = JNI_TRUE; } else if (strcmp(current, "n") == 0) { gdata->assertOn = JNI_FALSE; gdata->assertFatal = JNI_FALSE; } else { goto syntax_error; } current += strlen(current) + 1; } else if (strcmp(buf, "pause") == 0) { if ( !get_boolean(&str, &dopause) ) { goto syntax_error; } if ( dopause ) { do_pause(); } } else if (strcmp(buf, "coredump") == 0) { if ( !get_boolean(&str, &docoredump) ) { goto syntax_error; } } else if (strcmp(buf, "errorexit") == 0) { if ( !get_boolean(&str, &(gdata->doerrorexit)) ) { goto syntax_error; } } else if (strcmp(buf, "exitpause") == 0) { errmsg = "The exitpause option removed, use -XX:OnError"; goto bad_option_with_errmsg; } else if (strcmp(buf, "precrash") == 0) { errmsg = "The precrash option removed, use -XX:OnError"; goto bad_option_with_errmsg; } else if (strcmp(buf, "logfile") == 0) { /*LINTED*/ if (!get_tok(&str, current, (int)(end - current), ',')) { goto syntax_error; } logfile = current; current += strlen(current) + 1; } else if (strcmp(buf, "logflags") == 0) { /*LINTED*/ if (!get_tok(&str, current, (int)(end - current), ',')) { goto syntax_error; } /*LINTED*/ logflags = (unsigned)strtol(current, NULL, 0); } else if (strcmp(buf, "debugflags") == 0) { /*LINTED*/ if (!get_tok(&str, current, (int)(end - current), ',')) { goto syntax_error; } /*LINTED*/ gdata->debugflags = (unsigned)strtol(current, NULL, 0); } else if ( strcmp(buf, "suspend")==0 ) { if ( !get_boolean(&str, &suspendOnInit) ) { goto syntax_error; } } else if ( strcmp(buf, "server")==0 ) { if ( !get_boolean(&str, &isServer) ) { goto syntax_error; } } else if ( strcmp(buf, "strict")==0 ) { /* Obsolete, but accept it */ if ( !get_boolean(&str, &isStrict) ) { goto syntax_error; } } else if ( strcmp(buf, "quiet")==0 ) { if ( !get_boolean(&str, &(gdata->quiet)) ) { goto syntax_error; } } else if ( strcmp(buf, "onuncaught")==0 ) { if ( !get_boolean(&str, &initOnUncaught) ) { goto syntax_error; } } else if ( strcmp(buf, "mutf8")==0 ) { if ( !get_boolean(&str, &(gdata->modifiedUtf8)) ) { goto syntax_error; } } else if ( strcmp(buf, "stdalloc")==0 ) { /* Obsolete, but accept it */ if ( !get_boolean(&str, &useStandardAlloc) ) { goto syntax_error; } } else { goto syntax_error; } } /* Setup logging now */ if ( logfile!=NULL ) { setup_logging(logfile, logflags); (void)atexit(&atexit_finish_logging); } if (bagSize(transports) == 0) { errmsg = "no transport specified"; goto bad_option_with_errmsg; } /* * TO DO: Remove when multiple transports are allowed. (replace with * check below. */ if (bagSize(transports) > 1) { errmsg = "multiple transports are not supported in this release"; goto bad_option_with_errmsg; } if (!isServer) { jboolean specified = bagEnumerateOver(transports, checkAddress, NULL); if (!specified) { /* message already printed */ goto bad_option_no_msg; } } /* * The user has selected to wait for an exception before init happens */ if ((initOnException != NULL) || (initOnUncaught)) { initOnStartup = JNI_FALSE; if (launchOnInit == NULL) { /* * These rely on the launch=/usr/bin/foo * suboption, so it is an error if user did not * provide one. */ errmsg = "Specify launch=<command line> when using onthrow or onuncaught suboption"; goto bad_option_with_errmsg; } } return JNI_TRUE; syntax_error: ERROR_MESSAGE(("JDWP option syntax error: %s=%s", AGENTLIB, options)); return JNI_FALSE; bad_option_with_errmsg: ERROR_MESSAGE(("JDWP %s: %s=%s", errmsg, AGENTLIB, options)); return JNI_FALSE; bad_option_no_msg: ERROR_MESSAGE(("JDWP %s: %s=%s", "invalid option", AGENTLIB, options)); return JNI_FALSE; }
int main (int argc, char *argv[]) { int lower = 0; /* lower limit of log depth, if kept set to zero */ int higher = 0; /* upper limit of log depth, if kept set to zero */ /* process command line options */ int opt; /* selected option */ do { switch ((opt = getopt (argc, argv, "l:L:bh"))) { case 'l': /* log depth */ if (sscanf (optarg, "%d,%d", &lower, &higher) != 2) { fprintf (stderr, "%s: Bad argument to l option.\n", basename (argv[0])); printUsage (basename (argv[0])); return EXIT_FAILURE; } soSetProbe (lower, higher); break; case 'L': /* log file */ if ((fl = fopen (optarg, "w")) == NULL) { fprintf (stderr, "%s: Can't open log file \"%s\".\n", basename (argv[0]), optarg); printUsage (basename (argv[0])); return EXIT_FAILURE; } soOpenProbe (fl); break; case 'b': /* batch mode */ batch = 1; /* set batch mode for processing: no input messages are issued */ break; case 'h': /* help mode */ printUsage (basename (argv[0])); return EXIT_SUCCESS; case -1: break; default: fprintf (stderr, "%s: Wrong option.\n", basename (argv[0])); printUsage (basename (argv[0])); return EXIT_FAILURE; } } while (opt != -1); if ((argc - optind) != 1) /* check existence of mandatory argument: storage device name */ { fprintf (stderr, "%s: Wrong number of mandatory arguments.\n", basename (argv[0])); printUsage (basename (argv[0])); return EXIT_FAILURE; } if (fl == NULL) fl = stdout; /* if the switch -L was not used, set output to stdout */ else stderr = fl; /* if the switch -L was used, set stderr to log file */ /* check for storage device conformity */ char *devname; /* path to the storage device in the Linux file system */ struct stat st; /* file attributes */ devname = argv[optind]; if (stat (devname, &st) == -1) /* get file attributes */ { printError (-errno, basename (argv[0])); return EXIT_FAILURE; } if (st.st_size % BLOCK_SIZE != 0) /* check file size: the storage device must have a size in bytes multiple of block size */ { fprintf (stderr, "%s: Bad size of support file.\n", basename (argv[0])); return EXIT_FAILURE; } /* open an unbuffered communication channel with the storage device */ int status; /* status of operation */ if ((status = soOpenBufferCache (argv[optind], UNBUF)) != 0) { printError (status, basename (argv[0])); return EXIT_FAILURE; } /* process the command */ int cmdNumb; /* command number */ int t; /* test flag */ while (true) { if (batch == 0) printMenu (); if (batch == 0) printf("\nYour command: "); do { t = scanf ("%d", &cmdNumb); scanf ("%*[^\n]"); scanf ("%*c"); } while (t != 1); if (cmdNumb == 0) break; if ((cmdNumb > 0) && (cmdNumb < HDL_LEN)) hdl[cmdNumb](); else { notUsed(); if (batch != 0) break; } } /* close the unbuffered communication channel with the storage device */ if ((status = soCloseBufferCache ()) != 0) { printError (status, basename (argv[0])); return EXIT_FAILURE; } /* that's all */ if (batch == 0) printf ("Bye!\n"); return EXIT_SUCCESS; } /* end of main */
int main(int argc, char* argv[]) { if (argc < 3 ) { printUsage(argv); exit(2); } char* indexFileName = argv[1]; int samplecount = atoi(argv[2]); int index = 0, bytesRead = 0; FILE *indexFileDesc; int fd; int f; char* targetArray = (char*)malloc(BUFFSIZE); char* fileName = (char*)malloc(30); double mean_counteroverhead = 0, stddev_counteroverhead = 0,\ stddev_fileReadoverhead = 0, mean_fileReadoverhead= 0; double fileReadOverheadArray[samplecount]; unsigned long long int start = 0, end = 0; mean_counteroverhead = getCounteroverhead(samplecount, &stddev_counteroverhead); printCounterOverheadResults(samplecount, mean_counteroverhead, stddev_counteroverhead); bzero(fileName, sizeof(fileName)); indexFileDesc = fopen(indexFileName, "r"); int fileSize = 400; char c; while (fgets(fileName, 30, indexFileDesc)) { fileName[strlen(fileName)-1] = '\0'; printf("Gonna read file: \"%s\"; Clean the cache and press enter to continue...\n", fileName); c = getchar(); for(index = -1; index < samplecount; index++) { fd = open(fileName, O_RDONLY); start = count(); while ((bytesRead = read(fd, targetArray, BUFFSIZE)) > 0) { } end = count(); if (bytesRead == -1) { perror("Error while reading"); exit(2); } if (bytesRead == 0) { //perror("Read zero bytes"); } // omit the first sample as it will come from the disk; // For files which exceed the cache size, even further reads will come from disk if (index != -1) fileReadOverheadArray[index] = end-start-mean_counteroverhead; close(fd); } mean_fileReadoverhead = getMeanStddev(fileReadOverheadArray, samplecount, &stddev_fileReadoverhead); //printResult(samplecount, mean_fileReadoverhead, stddev_fileReadoverhead, "FILE READ - cycles"); //printResult(samplecount, mean_fileReadoverhead, stddev_fileReadoverhead, "FILE READ - cycles"); printf("%25s\t:%20f\t%20f\t%20f\n", fileName, getDurationinMilliSec(mean_fileReadoverhead),\ getDurationinMilliSec(stddev_fileReadoverhead),\ fileSize/getDurationinSec(mean_fileReadoverhead)); // printResult(samplecount, getDurationinMilliSec(mean_fileReadoverhead),\ // getDurationinMilliSec(stddev_fileReadoverhead), fileName); //getDurationinMilliSec(stddev_fileReadoverhead), "FILE READ - msecs"); bzero(fileName, sizeof(fileName)); fileSize += 400; } return 0; }
/* Show usage information */ static void showUsage(void) { printUsage(); quit(0); }
int main(int argc, char *argv[]) { // if(testme()) // return 0; if (argc == 2 && (strcmp(argv[0], "-h") == 0 || strcmp(argv[0], "--help") == 0)) { printUsage(argv[0]); return EXIT_SUCCESS; } if (argc != 3) { printUsage(argv[0]); return EXIT_FAILURE; } FILE * f; if ((f = fopen(argv[2], "r")) == NULL) { printf("Unable to open file '%s', aborting!\n", argv[2]); return EXIT_FAILURE; } FILE * fptrout = stdout; int line_count = 0; char line_buffer[LINE_SIZE]; while (fgets(line_buffer, LINE_SIZE, f) != NULL) { line_count++; } int file_length = ftell(f); rewind(f); char * * src = malloc(sizeof(char *) * line_count); char * * copy = malloc(sizeof(char *) * line_count); int i; for (i = 0; i < line_count; i++) { if (feof(f)) { printf("Not enough lines in file!\n"); fclose(f); return EXIT_FAILURE; } copy[i] = malloc(sizeof(char) * LINE_SIZE); fgets(copy[i], LINE_SIZE, f); trim(copy[i]); src[i] = strdup(copy[i]); } fclose(f); char * buffer = malloc(sizeof(char) * file_length); buffer[0] = '\0'; //Partitioning outputs const char * command = argv[1]; if (strcmp(command, "my_strlen") == 0) { for (i = 0; i < line_count; i++) { fprintf(fptrout, "length: %d\n", my_strlen(copy[i])); } } else if (strcmp(command, "my_countchar") == 0) { for (i = 0; i < line_count; i++) { fprintf(fptrout, "count(%c): %d\n", copy[i][0], my_countchar(copy[i], copy[i][0])); } } else if (strcmp(command, "my_strupper") == 0) { for (i = 0; i < line_count; i++) { my_strupper(copy[i]); fprintf(fptrout, "uppercase: %s\n", copy[i]); } } else if (strcmp(command, "my_strlower") == 0) { for (i = 0; i < line_count; i++) { my_strlower(copy[i]); fprintf(fptrout, "lowercase: %s\n", copy[i]); } } else if (strcmp(command, "my_strcat") == 0) { for (i = 0; i < line_count; i++) { my_strcat(copy[i], " "); my_strcat(copy[i], src[i]); fprintf(fptrout, "%s\n", copy[i]); } } else if (strcmp(command, "my_strncat") == 0) { for (i = 0; i < line_count; i++) { my_strncat(copy[i], " ", 2); my_strncat(copy[i], "........", 1); fprintf(fptrout, "%s\n", copy[i]); } } else if (strcmp(command, "my_strcpy") == 0) { for (i = 0; i < line_count; i++) { my_strcpy(copy[i], "Copying this String."); fprintf(fptrout, "%s\n", copy[i]); } } else if (strcmp(command, "my_strncpy") == 0) { for (i = 0; i < line_count; i++) { my_strncpy(copy[i], src[i], 5); fprintf(fptrout, "%s\n", copy[i]); } } else if (strcmp(command, "my_strstr") == 0) { for (i = 0; i < line_count; i++) { fprintf(fptrout, "%d\n", my_strstr(copy[i], src[i]) != NULL); } } else if (strcmp(command, "my_strinsert") == 0) { for (i = 0; i < line_count; i++) { my_strinsert(buffer, "\n", 0); my_strinsert(buffer, src[i], 0); } fprintf(fptrout, "[%s]\n", buffer); } else if (strcmp(command, "my_strdelete") == 0) { for (i = 0; i < line_count; i++) { my_strinsert(buffer, "\n", 0); my_strinsert(buffer, src[i], 0); my_strdelete(buffer, 0, 10); } fprintf(fptrout, "[%s]\n", buffer); } for (i = 0; i < line_count; i++) { free(copy[i]); free(src[i]); } free(src); free(copy); free(buffer); fclose(fptrout); return EXIT_SUCCESS; }
int test_validatechain_bc(int argc, char *argv[]) { PKIX_TrustAnchor *anchor = NULL; PKIX_List *anchors = NULL; PKIX_List *certs = NULL; PKIX_ProcessingParams *procParams = NULL; PKIX_ValidateParams *valParams = NULL; PKIX_ValidateResult *valResult = NULL; PKIX_PL_X500Name *subject = NULL; PKIX_ComCertSelParams *certSelParams = NULL; PKIX_CertSelector *certSelector = NULL; char *trustedCertFile = NULL; char *chainCertFile = NULL; PKIX_PL_Cert *trustedCert = NULL; PKIX_PL_Cert *chainCert = NULL; PKIX_UInt32 chainLength = 0; PKIX_UInt32 i = 0; PKIX_UInt32 j = 0; PKIX_UInt32 actualMinorVersion; PKIX_VerifyNode *verifyTree = NULL; PKIX_PL_String *verifyString = NULL; PKIX_TEST_STD_VARS(); if (argc < 3){ printUsage(); return (0); } startTests("ValidateChainBasicConstraints"); PKIX_TEST_EXPECT_NO_ERROR( PKIX_PL_NssContext_Create(0, PKIX_FALSE, NULL, &plContext)); chainLength = (argc - j) - 2; /* create processing params with list of trust anchors */ trustedCertFile = argv[1+j]; trustedCert = createCert(trustedCertFile); PKIX_TEST_EXPECT_NO_ERROR (PKIX_PL_Cert_GetSubject(trustedCert, &subject, plContext)); PKIX_TEST_EXPECT_NO_ERROR (PKIX_ComCertSelParams_Create(&certSelParams, plContext)); PKIX_TEST_EXPECT_NO_ERROR(PKIX_ComCertSelParams_SetBasicConstraints (certSelParams, -1, plContext)); PKIX_TEST_EXPECT_NO_ERROR (PKIX_CertSelector_Create (NULL, NULL, &certSelector, plContext)); PKIX_TEST_EXPECT_NO_ERROR(PKIX_CertSelector_SetCommonCertSelectorParams (certSelector, certSelParams, plContext)); PKIX_TEST_DECREF_BC(subject); PKIX_TEST_EXPECT_NO_ERROR(PKIX_TrustAnchor_CreateWithCert (trustedCert, &anchor, plContext)); PKIX_TEST_EXPECT_NO_ERROR(PKIX_List_Create(&anchors, plContext)); PKIX_TEST_EXPECT_NO_ERROR (PKIX_List_AppendItem (anchors, (PKIX_PL_Object *)anchor, plContext)); PKIX_TEST_EXPECT_NO_ERROR(PKIX_ProcessingParams_Create (anchors, &procParams, plContext)); PKIX_TEST_EXPECT_NO_ERROR(PKIX_ProcessingParams_SetRevocationEnabled (procParams, PKIX_FALSE, plContext)); PKIX_TEST_EXPECT_NO_ERROR (PKIX_ProcessingParams_SetTargetCertConstraints (procParams, certSelector, plContext)); PKIX_TEST_DECREF_BC(certSelector); /* create cert chain */ PKIX_TEST_EXPECT_NO_ERROR(PKIX_List_Create(&certs, plContext)); for (i = 0; i < chainLength; i++){ chainCertFile = argv[i + (2+j)]; chainCert = createCert(chainCertFile); PKIX_TEST_EXPECT_NO_ERROR(PKIX_List_AppendItem (certs, (PKIX_PL_Object *)chainCert, plContext)); PKIX_TEST_DECREF_BC(chainCert); } /* create validate params with processing params and cert chain */ PKIX_TEST_EXPECT_NO_ERROR(PKIX_ValidateParams_Create (procParams, certs, &valParams, plContext)); /* validate cert chain using processing params and return valResult */ PKIX_TEST_EXPECT_NO_ERROR(PKIX_ValidateChain (valParams, &valResult, &verifyTree, plContext)); if (valResult != NULL){ printf("SUCCESSFULLY VALIDATED with Basic Constraint "); printf("Cert Selector minimum path length to be -1\n"); PKIX_TEST_DECREF_BC(valResult); } PKIX_TEST_EXPECT_NO_ERROR(PKIX_PL_Object_ToString ((PKIX_PL_Object*)verifyTree, &verifyString, plContext)); (void) printf("verifyTree is\n%s\n", verifyString->escAsciiString); PKIX_TEST_DECREF_BC(verifyString); PKIX_TEST_DECREF_BC(verifyTree); PKIX_TEST_EXPECT_NO_ERROR(PKIX_ComCertSelParams_SetBasicConstraints (certSelParams, 6, plContext)); /* validate cert chain using processing params and return valResult */ PKIX_TEST_EXPECT_ERROR(PKIX_ValidateChain (valParams, &valResult, &verifyTree, plContext)); if (valResult != NULL){ printf("SUCCESSFULLY VALIDATED with Basic Constraint "); printf("Cert Selector minimum path length to be 6\n"); } PKIX_TEST_DECREF_BC(trustedCert); PKIX_TEST_DECREF_BC(anchor); PKIX_TEST_DECREF_BC(anchors); PKIX_TEST_DECREF_BC(certs); PKIX_TEST_DECREF_BC(procParams); cleanup: if (PKIX_TEST_ERROR_RECEIVED){ printf("FAILED TO VALIDATE\n"); } PKIX_TEST_EXPECT_NO_ERROR(PKIX_PL_Object_ToString ((PKIX_PL_Object*)verifyTree, &verifyString, plContext)); (void) printf("verifyTree is\n%s\n", verifyString->escAsciiString); PKIX_TEST_DECREF_AC(verifyString); PKIX_TEST_DECREF_AC(verifyTree); PKIX_TEST_DECREF_AC(certSelParams); PKIX_TEST_DECREF_AC(valResult); PKIX_TEST_DECREF_AC(valParams); PKIX_TEST_RETURN(); PKIX_Shutdown(plContext); endTests("ValidateChainBasicConstraints"); return (0); }
int main(int argc, char **argv) { char *device = "/dev/ttySO"; char *address = "127.0.0.1"; int port = 9999; int c; opterr = 0; while ((c = getopt (argc, argv, "hvd:a:p:")) != -1) switch (c) { case 'v': verbose++; break; case 'd': device = optarg; break; case 'a': address = optarg; break; case 'p': port = atoi(optarg); break; case '?': if (optopt == 'd' || optopt == 'a' || optopt == 'p') fprintf (stderr, "Option -%c requires an argument.\n", optopt); else if (isprint (optopt)) fprintf (stderr, "Unknown option `-%c'.\n", optopt); else fprintf (stderr, "Unknown option character `\\x%x'.\n", optopt); return 1; case 'h': default: printUsage(argv[0]); return 1; } // Install signal handlers signal(SIGINT, signalCallbackHandler); int serialport_fd = -1; int udp_fd = -1; // Initialize destination address struct sockaddr_in dest; dest.sin_family = AF_INET; dest.sin_addr.s_addr = inet_addr(address); dest.sin_port = htons(port); #define MAX_DATA_LEN 200 unsigned char buffer[MAX_DATA_LEN]; unsigned char message[MAX_DATA_LEN]; for (;;) { /* * Error tolerant solution. * * Try to open serial port and udp socket on every round, * if open has failed. * */ if ( serialport_fd < 0 ) { // Open the serial port if (verbose) printf("Open serial port: %s\n", device); serialport_fd = open(device, O_RDWR | O_NOCTTY); // | O_NDELAY if (serialport_fd < 0) { fprintf(stderr, "Failed to open %s: %s\n", device, strerror(errno)); //return 1; } // Initialize serial port if (initSerialPort(serialport_fd) == -1) { fprintf(stderr, "Failed to set serial port: %s\n", strerror(errno)); //return 1; } } if ( udp_fd < 0 ) { // Open UDP socket udp_fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (udp_fd < 0) { fprintf(stderr, "Failed to open UDP socket: %s\n", strerror(errno)); //return 1; } if (verbose) printf("UDP address %s:%u\n", address, port); } int start_found = FALSE; int index = 0; /* unsigned char testdata[] = "\x01\x02" \ "\x5C\x00\x20\x6B\x00\x4B" \ "\x5C\x00\x20\x69\x00\x49\xC0\x69\x00\xA9" \ "\x5C\x00\x20\x68\x50\x01\xA8\x1F\x01\x00\xA8\x64\x00\xFD" \ "\xA7\xD0\x03\x44\x9C\x1E\x00\x4F\x9C\xA0\x00\x50\x9C\x78" \ "\x00\x51\x9C\x03\x01\x52\x9C\x1B\x01\x87\x9C\x14\x01\x4E" \ "\x9C\xC6\x01\x47\x9C\x01\x01\x15\xB9\xB0\xFF\x3A\xB9\x4B" \ "\x00\xC9\xAF\x00\x00\x48\x9C\x0D\x01\x4C\x9C\xE7\x00\x4B" \ "\x9C\x00\x00\xFF\xFF\x00\x00\xFF\xFF\x00\x00\xFF\xFF\x00" \ "\x00\x45"; ssize_t len = sizeof(testdata); memcpy( buffer, testdata, len); */ if (serialport_fd > 0) { ssize_t len = 0; while ((len = read(serialport_fd, buffer, MAX_DATA_LEN)) > 0) { for (int i = 0; i < len; i++) { if (verbose) printf("%02X ", buffer[i]); if (start_found == FALSE && buffer[i] == 0x5C) { start_found = TRUE; index = 0; } if (start_found) { if ((index+1) >= MAX_DATA_LEN) { start_found = FALSE; } else { message[index++] = buffer[i]; int msglen = checkMessage(message, index); switch (msglen) { case 0: // Ok, but not ready break; case -1: // Invalid message start_found = FALSE; break; case -2: // Checksum error sendNak(serialport_fd); start_found = FALSE; break; default: if (verbose) printf("Valid message received, len=%u\n", msglen); sendAck(serialport_fd); // send UDP packet if message is a data packet // if data contains 0x5C (start character), message len can be bigger than 0x50 if (buffer[0] == 0x5C && buffer[1] == 0x00 && buffer[2] == 0x20 && buffer[3] == 0x68 && buffer[4] >= 0x50) { if (verbose) printf("Send UDP data to %s:%u\n", address, port); if (verbose) printMessage( message, msglen); if (sendto(udp_fd, message, msglen + 1, 0 , (struct sockaddr *)&dest, sizeof(dest)) == -1) { fprintf(stderr, "Failed to send udp packet: %s\n", strerror(errno)); } } // Wait new message start_found = FALSE; break; } } } } } if (len < 0 ) { if (errno == EINTR) { if (verbose) printf("Interrupted\n"); break; } else { fprintf(stderr, "Read failed: %s\n", strerror(errno)); sleep(1); } } else if (len == 0) { if (verbose) printf("Read return 0\n"); } } else { sleep(1); } } close(serialport_fd); close(udp_fd); return 0; }
int main(int argc, char* argv[]) { StringSet targets, configurations, schemes; String sdkRoot, projectPath, xcconfigPath, workspacePath; String logVerbosity("warning"); int projectSet = 0; int workspaceSet = 0; int interactiveFlag = 0; int relativeSdkFlag = 0; int allTargets = 0; int allSchemes = 0; int mode = GenerateMode; static struct option long_options[] = { {"version", no_argument, 0, 0}, {"usage", no_argument, 0, 0}, {"help", no_argument, 0, 0}, {"interactive", no_argument, &interactiveFlag, 1}, {"loglevel", required_argument, 0, 0}, {"sdk", required_argument, 0, 0}, {"list", no_argument, &mode, ListMode}, {"project", required_argument, &projectSet, 1}, {"target", required_argument, 0, 0}, {"alltargets", no_argument, &allTargets, 1}, {"configuration", required_argument, 0, 0}, {"xcconfig", required_argument, 0, 0}, {"workspace", required_argument, &workspaceSet, 1}, {"scheme", required_argument, 0, 0}, {"allschemes", required_argument, &allSchemes, 1}, {"relativepath", no_argument, &relativeSdkFlag, 1}, {0, 0, 0, 0} }; int numOptions = sizeof(long_options) / sizeof(struct option) - 1; while (1) { int option_index = 0; int c = getopt_long_only(argc, argv, "", long_options, &option_index); if (c == -1) break; else if (c || option_index < 0 || option_index >= numOptions) printUsage(argv[0], false, EXIT_FAILURE); // Process options switch (option_index) { case 0: printVersion(argv[0]); break; case 1: printUsage(argv[0], false, EXIT_SUCCESS); break; case 2: printUsage(argv[0], true, EXIT_SUCCESS); break; case 4: logVerbosity = strToLower(optarg); break; case 5: sdkRoot = optarg; break; case 7: projectPath = optarg; break; case 8: targets.insert(optarg); break; case 10: configurations.insert(optarg); break; case 11: xcconfigPath = optarg; break; case 12: workspacePath = optarg; break; case 13: schemes.insert(optarg); break; default: // Do nothing break; } } // Set AI Telemetry_Init TELEMETRY_INIT(L"AIF-23c336e0-1e7e-43ba-a5ce-eb9dc8a06d34"); if (checkTelemetryOptIn()) { TELEMETRY_ENABLE(); } else { TELEMETRY_DISABLE(); } TELEMETRY_SET_INTERNAL(isMSFTInternalMachine()); String machineID = getMachineID(); if (!machineID.empty()) { TELEMETRY_SET_MACHINEID(machineID.c_str()); } TELEMETRY_EVENT_DATA(L"VSImporterStart", "WinStore10"); // Process non-option ARGV-elements VariableCollectionManager& settingsManager = VariableCollectionManager::get(); while (optind < argc) { String arg = argv[optind]; if (arg == "/?") { // Due to issue 6715724, flush before exiting TELEMETRY_EVENT_DATA(L"VSImporterIncomplete", "printUsage"); TELEMETRY_FLUSH(); printUsage(argv[0], true, EXIT_SUCCESS); } else if (arg.find_first_of('=') != String::npos) { settingsManager.processGlobalAssignment(arg); } else { sbValidateWithTelemetry(0, "Unsupported argument: " + arg); } optind++; } // Set output format settingsManager.setGlobalVar("VSIMPORTER_OUTPUT_FORMAT", "WinStore10"); // Set logging level SBLogLevel logLevel; if (logVerbosity == "debug") logLevel = SB_DEBUG; else if (logVerbosity == "info") logLevel = SB_INFO; else if (logVerbosity == "warning") logLevel = SB_WARN; else if (logVerbosity == "error") logLevel = SB_ERROR; else if (!logVerbosity.empty()) { sbValidateWithTelemetry(0, "Unrecognized logging verbosity: " + logVerbosity); } SBLog::setVerbosity(logLevel); // Look for a project file in current directory, if one hasn't been explicitly specified if (!projectSet && !workspaceSet) { StringList projects; findFiles(".", "*.xcodeproj", DT_DIR, false, projects); StringList workspaces; findFiles(".", "*.xcworkspace", DT_DIR, false, workspaces); if (!workspaces.empty()) { sbValidateWithTelemetry(workspaces.size() == 1, "Multiple workspaces found. Select the workspace to use with the -workspace option."); workspacePath = workspaces.front(); workspaceSet = 1; } else if (!projects.empty()) { sbValidateWithTelemetry(projects.size() == 1, "Multiple projects found. Select the project to use with the -project option."); projectPath = projects.front(); projectSet = 1; } else { sbValidateWithTelemetry(0, "The current directory does not contain a project or workspace."); } } // Set the architecture String arch = "msvc"; settingsManager.setGlobalVar("ARCHS", arch); settingsManager.setGlobalVar("CURRENT_ARCH", arch); // Make sure workspace arguments are valid if (workspaceSet) { sbValidateWithTelemetry(!projectSet, "Cannot specify both a project and a workspace."); sbValidateWithTelemetry(targets.empty(), "Cannot specify target(s) when specifying a workspace."); } // Disallow specifying schemes and targets together sbValidateWithTelemetry((schemes.empty() && !allSchemes) || (targets.empty() && !allTargets), "Cannot specify schemes and targets together."); // Process allTargets and allSchemes flags if (allSchemes) schemes.clear(); if (allTargets) targets.clear(); // Initialize global settings String binaryDir = sb_dirname(getBinaryLocation()); sbValidateWithTelemetry(!binaryDir.empty(), "Failed to resolve binary directory."); settingsManager.setGlobalVar("VSIMPORTER_BINARY_DIR", binaryDir); settingsManager.setGlobalVar("VSIMPORTER_INTERACTIVE", interactiveFlag ? "YES" : "NO"); settingsManager.setGlobalVar("VSIMPORTER_RELATIVE_SDK_PATH", relativeSdkFlag ? "YES" : "NO"); if (!sdkRoot.empty()) { sdkRoot = joinPaths(getcwd(), sdkRoot); } else { sdkRoot = joinPaths(binaryDir, ".."); } settingsManager.setGlobalVar("WINOBJC_SDK_ROOT", sdkRoot); // Add useful environment variables to global settings String username; sbValidateWithTelemetry(sb_getenv("USERNAME", username), "Failed to get current username."); settingsManager.setGlobalVar("USER", username); // Read xcconfig file specified from the command line if (!xcconfigPath.empty()) settingsManager.processGlobalConfigFile(xcconfigPath); // Read xcconfig file specified by the XCODE_XCCONFIG_FILE environment variable String xcconfigFile; if (sb_getenv("XCODE_XCCONFIG_FILE", xcconfigFile)) settingsManager.processGlobalConfigFile(xcconfigFile); // Validate WinObjC SDK directory checkWinObjCSDK(); // Create a workspace SBWorkspace *mainWorkspace; if (workspaceSet) { mainWorkspace = SBWorkspace::createFromWorkspace(workspacePath); } else if (projectSet) { mainWorkspace = SBWorkspace::createFromProject(projectPath); } else { sbAssertWithTelemetry(0); // non-reachable } if (mode == ListMode) { mainWorkspace->printSummary(); } else if (mode == GenerateMode) { if (allTargets) { mainWorkspace->queueAllTargets(configurations); } else if (projectSet) { mainWorkspace->queueTargets(targets, configurations); } else if (workspaceSet) { mainWorkspace->queueSchemes(schemes, configurations); } else { sbAssertWithTelemetry(0); // non-reachable } mainWorkspace->generateFiles(); } else { sbAssertWithTelemetry(0); // non-reachable } TELEMETRY_EVENT_DATA(L"VSImporterComplete", "WinStore10"); TELEMETRY_FLUSH(); return EXIT_SUCCESS; }
int main(int argc, char *argv[]) { int i; FILE *fp; int fd; char *path = NULL; size_t off = 0, len = 0; char optchr; enum EnumMode mode = EnumModePosix; while (-1 != (optchr = getopt(argc, argv, "plLh"))) { switch (optchr) { case EnumModePosix: case EnumModeLinux: case EnumModeLinuxWithFlag: mode = optchr; break; case 'h': default: printUsage(); } } for (i = optind; i < argc; ++i) { if (NULL == path) path = argv[i]; else if ( ! len) len = myAtoi(argv[i]); else if ( ! off) off = myAtoi(argv[i]); } if (NULL == path) printUsage(); if (0 == len) len = (size_t)100 * 1024 * 1024; fp = fopen(path, "w"); if (NULL == fp) myPerror("fopen", 42); fd = fileno(fp); if (EnumModePosix == mode) { const int rc = posix_fallocate(fd, off, len); if (RC_OK != rc) { char buf[BUFLEN]; fprintf(stderr, "posix_fallocate: %s", strerror_r(rc, buf, sizeof buf)); exit(40); } } else { const int flag = (EnumModeLinuxWithFlag == mode ? FALLOC_FL_KEEP_SIZE : 0); if (RC_NG == fallocate(fd, flag, off, len)) myPerror("fallocate", 44); } fclose(fp); return 0; }
int main(int argc, char *argv[]) { TPM_RC rc = 0; int i; /* argc iterator */ ClearControl_In in; char authHandleChar = 0; const char *authPassword = NULL; int state = 1; TPMI_SH_AUTH_SESSION sessionHandle0 = TPM_RS_PW; unsigned int sessionAttributes0 = 0; TPMI_SH_AUTH_SESSION sessionHandle1 = TPM_RH_NULL; unsigned int sessionAttributes1 = 0; TPMI_SH_AUTH_SESSION sessionHandle2 = TPM_RH_NULL; unsigned int sessionAttributes2 = 0; TSE_SetProperty(TPM_TRACE_LEVEL, "1"); for (i=1 ; (i<argc) && (rc == 0) ; i++) { if (strcmp(argv[i],"-hi") == 0) { i++; if (i < argc) { authHandleChar = argv[i][0]; } else { printf("Missing parameter for -hi\n"); printUsage(); } } else if (strcmp(argv[i],"-pwda") == 0) { i++; if (i < argc) { authPassword = argv[i]; } else { printf("-pwda option needs a value\n"); printUsage(); } } else if (strcmp(argv[i],"-state") == 0) { i++; if (i < argc) { state = atoi(argv[i]); } else { printf("-state option needs a value\n"); printUsage(); } } else if (strcmp(argv[i],"-se0") == 0) { i++; if (i < argc) { sscanf(argv[i],"%x", &sessionHandle0); } else { printf("Missing parameter for -se0\n"); printUsage(); } i++; if (i < argc) { sscanf(argv[i],"%x", &sessionAttributes0); if (sessionAttributes0 > 0xff) { printf("Out of range session attributes for -se0\n"); printUsage(); } } else { printf("Missing parameter for -se0\n"); printUsage(); } } else if (strcmp(argv[i],"-se1") == 0) { i++; if (i < argc) { sscanf(argv[i],"%x", &sessionHandle1); } else { printf("Missing parameter for -se1\n"); printUsage(); } i++; if (i < argc) { sscanf(argv[i],"%x", &sessionAttributes1); if (sessionAttributes1 > 0xff) { printf("Out of range session attributes for -se1\n"); printUsage(); } } else { printf("Missing parameter for -se1\n"); printUsage(); } } else if (strcmp(argv[i],"-se2") == 0) { i++; if (i < argc) { sscanf(argv[i],"%x", &sessionHandle2); } else { printf("Missing parameter for -se2\n"); printUsage(); } i++; if (i < argc) { sscanf(argv[i],"%x", &sessionAttributes2); if (sessionAttributes2 > 0xff) { printf("Out of range session attributes for -se2\n"); printUsage(); } } else { printf("Missing parameter for -se2\n"); printUsage(); } } else if (strcmp(argv[i],"-h") == 0) { printUsage(); } else if (strcmp(argv[i],"-v") == 0) { verbose = TRUE; TSE_SetProperty(TPM_TRACE_LEVEL, "2"); } else { printf("\n%s is not a valid option\n", argv[i]); printUsage(); } } /* Table 50 - TPMI_RH_HIERARCHY primaryHandle */ if (rc == 0) { if (authHandleChar == 'l') { in.auth = TPM_RH_LOCKOUT; } else if (authHandleChar == 'p') { in.auth = TPM_RH_PLATFORM; } else { printf("Missing or illegal -hi\n"); printUsage(); } } if (rc == 0) { if (state != 0) { in.disable = YES; } else { in.disable = NO; } } /* call TSE to execute the command */ if (rc == 0) { rc = TSE_Execute(NULL, (COMMAND_PARAMETERS *)&in, NULL, TPM_CC_ClearControl, sessionHandle0, authPassword, sessionAttributes0, sessionHandle1, NULL, sessionAttributes1, sessionHandle2, NULL, sessionAttributes2, TPM_RH_NULL, NULL, 0); } if (rc == 0) { if (verbose) printf("clearcontrol: success\n"); } else { const char *msg; const char *submsg; const char *num; printf("clearcontrol: failed, rc %08x\n", rc); TSEResponseCode_toString(&msg, &submsg, &num, rc); printf("%s%s%s\n", msg, submsg, num); rc = EXIT_FAILURE; } return rc; }
int main(int argc, char* argv[]) { #ifdef Q_OS_WIN _setmode(1, _O_BINARY); _setmode(2, _O_BINARY); #endif // Suppress debug output from Qt if not started with -v bool suppressQtDebugOutput = true; for (int i = 1; i < argc; ++i) { if (!qstrcmp(argv[i], "-v")) { suppressQtDebugOutput = false; break; } } // Has to be done before QApplication is constructed in case // QApplication itself produces debug output. if (suppressQtDebugOutput) qInstallMessageHandler(messageHandler); WebKit::QtTestSupport::initializeTestFonts(); QApplication::setStyle(QStyleFactory::create(QLatin1String("windows"))); QApplication::setDesktopSettingsAware(false); QApplication app(argc, argv); app.setQuitOnLastWindowClosed(false); QCoreApplication::setAttribute(Qt::AA_Use96Dpi, true); WTFInstallReportBacktraceOnCrashHook(); QStringList args = app.arguments(); if (args.count() < (!suppressQtDebugOutput ? 3 : 2)) { printUsage(); exit(1); } // Remove the first arguments, it is application name itself args.removeAt(0); DumpRenderTree dumper; int index = args.indexOf(QLatin1String("--stdout")); if (index != -1) { QString fileName = takeOptionValue(args, index); dumper.setRedirectOutputFileName(fileName); if (fileName.isEmpty() || !freopen(qPrintable(fileName), "w", stdout)) { fprintf(stderr, "STDOUT redirection failed."); exit(1); } } index = args.indexOf(QLatin1String("--stderr")); if (index != -1) { QString fileName = takeOptionValue(args, index); dumper.setRedirectErrorFileName(fileName); if (!freopen(qPrintable(fileName), "w", stderr)) { fprintf(stderr, "STDERR redirection failed."); exit(1); } } index = args.indexOf("--pixel-tests"); if (index == -1) index = args.indexOf("-p"); if (index != -1) { dumper.setShouldDumpPixelsForAllTests(); args.removeAt(index); } QWebDatabase::removeAllDatabases(); index = args.indexOf(QLatin1String("--timeout")); if (index != -1) { int timeout = takeOptionValue(args, index).toInt(); dumper.setTimeout(timeout); } index = args.indexOf(QLatin1String("--no-timeout")); if (index != -1) { dumper.setShouldTimeout(false); args.removeAt(index); } index = args.indexOf(QLatin1String("-")); if (index != -1) { args.removeAt(index); // Continue waiting in STDIN for more test case after process one test case QObject::connect(&dumper, SIGNAL(ready()), &dumper, SLOT(readLine()), Qt::QueuedConnection); // Read and only read the first test case, ignore the others if (args.size() > 0) { // Process the argument first dumper.processLine(args[0]); } else QTimer::singleShot(0, &dumper, SLOT(readLine())); } else { // Go into standalone mode // Standalone mode need at least one test case if (args.count() < 1) { printUsage(); exit(1); } dumper.processArgsLine(args); } return app.exec(); }
int main (int argc, char *argv[]) { Display *dpy; int nScreens, screenNum, i; enum INFO_FUNC func = LIST; char *funcArg = NULL; char *dpyName = NULL; GetScreenDriver = (glXGetScreenDriver_t *)glXGetProcAddressARB ((const GLubyte *)"glXGetScreenDriver"); GetDriverConfig = (glXGetDriverConfig_t *)glXGetProcAddressARB ((const GLubyte *)"glXGetDriverConfig"); if (!GetScreenDriver || !GetDriverConfig) { fprintf (stderr, "libGL is too old.\n"); return 1; } /* parse the command line */ for (i = 1; i < argc; ++i) { char **argPtr = NULL; if (!strcmp (argv[i], "-display")) argPtr = &dpyName; else if (!strcmp (argv[i], "nscreens")) func = NSCREENS; else if (!strcmp (argv[i], "driver")) { func = DRIVER; argPtr = &funcArg; } else if (!strcmp (argv[i], "options")) { func = OPTIONS; argPtr = &funcArg; } else { printUsage (); return 1; } if (argPtr) { if (++i == argc) { printUsage (); return 1; } *argPtr = argv[i]; } } /* parse screen number argument */ if (func == DRIVER || func == OPTIONS) { if (sscanf (funcArg, "%i", &screenNum) != 1) screenNum = -1; else if (screenNum < 0) { fprintf (stderr, "Negative screen number \"%s\".\n", funcArg); return 1; } } /* if the argument to the options command is a driver name, we can handle * it without opening an X connection */ if (func == OPTIONS && screenNum == -1) { const char *options = (*GetDriverConfig) (funcArg); if (!options) { fprintf (stderr, "Driver \"%s\" is not installed or does not support configuration.\n", funcArg); return 1; } printf ("%s", options); if (isatty (STDOUT_FILENO)) printf ("\n"); return 0; } /* driver command needs a valid screen number */ else if (func == DRIVER && screenNum == -1) { fprintf (stderr, "Invalid screen number \"%s\".\n", funcArg); return 1; } /* open display and count the number of screens */ if (!(dpy = XOpenDisplay (dpyName))) { fprintf (stderr, "Error: Couldn't open display\n"); return 1; } nScreens = ScreenCount (dpy); /* final check on the screen number argument (if any)*/ if ((func == DRIVER || func == OPTIONS) && screenNum >= nScreens) { fprintf (stderr, "Screen number \"%d\" out of range.\n", screenNum); return 1; } switch (func) { case NSCREENS: printf ("%d", nScreens); if (isatty (STDOUT_FILENO)) printf ("\n"); break; case DRIVER: { const char *name = (*GetScreenDriver) (dpy, screenNum); if (!name) { fprintf (stderr, "Screen \"%d\" is not direct rendering capable.\n", screenNum); return 1; } printf ("%s", name); if (isatty (STDOUT_FILENO)) printf ("\n"); break; } case OPTIONS: { const char *name = (*GetScreenDriver) (dpy, screenNum), *options; if (!name) { fprintf (stderr, "Screen \"%d\" is not direct rendering capable.\n", screenNum); return 1; } options = (*GetDriverConfig) (name); if (!options) { fprintf (stderr, "Driver \"%s\" is not installed or does not support configuration.\n", name); return 1; } printf ("%s", options); if (isatty (STDOUT_FILENO)) printf ("\n"); break; } case LIST: for (i = 0; i < nScreens; ++i) { const char *name = (*GetScreenDriver) (dpy, i); if (name) printf ("Screen %d: %s\n", i, name); else printf ("Screen %d: not direct rendering capable.\n", i); } } return 0; }
void Updater::checkNewestVersion() { connect(socket, &Socket::connected, [this](){ state_ = State::CHK_VERSION; QJsonDocument doc; QJsonObject obj; obj.insert("request", QJsonValue(QString("check"))); doc.setObject(obj); socket->sendData(doc.toJson()); }); connect(socket, &Socket::error, [this](){ switch(state_){ case State::CHK_VERSION: state_ = State::CHK_ERROR; break; case State::DOWNLOAD_NEW: state_ = State::DOWNLOAD_ERROR; break; case State::OVERLAP: state_ = State::OVERLAP_ERROR; break; default: state_ = State::UNKNOWN_ERROR; } qDebug()<<socket->errorString(); }); connect(socket, &Socket::newData, [this](const QByteArray& data){ QJsonDocument doc = QJsonDocument::fromJson(data); QJsonObject obj = doc.object(); if(obj.isEmpty()){ state_ = State::CHK_ERROR; qDebug()<<"Check version error!"; quit(); } QJsonObject info = obj.value("info").toObject(); if(info.isEmpty()){ state_ = State::CHK_ERROR; qDebug()<<"Check version error!"; quit(); } QString version = info.value("version").toString().trimmed(); QString changelog = info.value("changelog").toString(); int level = info.value("level").toDouble(); QUrl url = QUrl::fromUserInput(DOWNLOAD_URL); QString fetched_url = info.value("url").toString(); if(!fetched_url.isEmpty()){ url = QUrl::fromUserInput(fetched_url); } QStringList commandList = qApp->arguments(); // --version should be considered first int index = commandList.lastIndexOf("--version"); // then we check if there is -v index = index>0?index:commandList.lastIndexOf("-v"); if(index < 0 || index >= commandList.count()){ qDebug()<<"parsing error!"<<"cannot find --version or -v"; printUsage(); quit(); } QString old_version = commandList[index+1].trimmed(); if(old_version.isEmpty()){ qDebug()<<"parsing error!"<<"version number is empty"; printUsage(); quit(); } if(version != old_version){ QMessageBox msgBox; msgBox.setText(tr("New version!")); if(level < 3) { msgBox.setIcon(QMessageBox::Information); msgBox.setText(tr("There's a new version of Mr.Paint.\n" "We suggest you download it here: %1") .arg(url.toDisplayString())); }else{ msgBox.setIcon(QMessageBox::Warning); msgBox.setText(tr("There's a critical update of Mr.Paint.\n" "You can connect to server ONLY if you've updated: %1") .arg(url.toDisplayString())); } if(!changelog.isEmpty()){ msgBox.setDetailedText(changelog); } msgBox.exec(); quit(); } }); socket->connectToHost(QHostAddress(SERVER_ADDRESS), SERVER_PORT); return; }
void processArgs(int argc, char **argv) { globalArgs.attack_port = 0; globalArgs.syn_delay = DEFAULT_SYN_DELAY; globalArgs.payload_size = 0; int opt = 0; while((opt = getopt(argc, argv, optString)) != -1) { switch(opt) { case 'p': loadPayload(optarg); break; case 'd': globalArgs.syn_delay = atoi(optarg); if(globalArgs.syn_delay == 0) printUsage("Invalid delay."); break; case 'h': case '?': printUsage(NULL); default: break; } } char **remArgv = argv + optind; int remArgc = argc - optind; if(remArgc > 2) printUsage("Too many arguments."); if(remArgc < 2) printUsage("Too few arguments."); int ip_index = 0; int iface_index = 1; // If they put the interface before the ip:port, swap the indexes. if(get_iface_ip(&globalArgs.iface_addr, remArgv[iface_index]) == 0) { ip_index = 1; iface_index = 0; if(get_iface_ip(&globalArgs.iface_addr, remArgv[iface_index]) == 0) printUsage("Invalid interface."); } char *ip = remArgv[ip_index]; char *port = remArgv[ip_index]; while(*port != ':' && *port != '\0') port++; if(*port == '\0') printUsage("Please specify a port."); *port = '\0'; port++; globalArgs.attack_port = atoi(port); if(globalArgs.attack_port == 0) printUsage("Invalid port."); if(inet_aton(ip, &globalArgs.attack_ip) == 0) printUsage("Invalid IP address."); printf("[+] Sending packets from %s (%s)\n", remArgv[iface_index], inet_ntoa(globalArgs.iface_addr.sin_addr)); printf("[+] Attacking: %s:%hu...\n", ip, globalArgs.attack_port); }
void Foam::argList::parse ( bool checkArgs, bool checkOpts, bool initialise ) { // Help/documentation options: // -help print the usage // -doc display application documentation in browser // -srcDoc display source code in browser if ( options_.found("help") || options_.found("doc") || options_.found("srcDoc") ) { if (options_.found("help")) { printUsage(); } // only display one or the other if (options_.found("srcDoc")) { displayDoc(true); } else if (options_.found("doc")) { displayDoc(false); } ::exit(0); } // Print the usage message and exit if the number of arguments is incorrect if (!check(checkArgs, checkOpts)) { FatalError.exit(); } if (initialise) { string dateString = clock::date(); string timeString = clock::clockTime(); // Print the banner once only for parallel runs if (Pstream::master() && bannerEnabled) { IOobject::writeBanner(Info, true) << "Build : " << Foam::FOAMbuild << nl << "Exec : " << argListStr_.c_str() << nl << "Date : " << dateString.c_str() << nl << "Time : " << timeString.c_str() << nl << "Host : " << hostName() << nl << "PID : " << pid() << endl; } jobInfo.add("startDate", dateString); jobInfo.add("startTime", timeString); jobInfo.add("userName", userName()); jobInfo.add("foamVersion", word(FOAMversion)); jobInfo.add("code", executable_); jobInfo.add("argList", argListStr_); jobInfo.add("currentDir", cwd()); jobInfo.add("PPID", ppid()); jobInfo.add("PGID", pgid()); // add build information - only use the first word { std::string build(Foam::FOAMbuild); std::string::size_type found = build.find(' '); if (found != std::string::npos) { build.resize(found); } jobInfo.add("foamBuild", build); } } // Case is a single processor run unless it is running parallel int nProcs = 1; // Roots if running distributed fileNameList roots; // If this actually is a parallel run if (parRunControl_.parRun()) { // For the master if (Pstream::master()) { // establish rootPath_/globalCase_/case_ for master getRootCase(); // See if running distributed (different roots for different procs) label dictNProcs = -1; fileName source; if (options_.found("roots")) { source = "-roots"; IStringStream is(options_["roots"]); roots = readList<fileName>(is); if (roots.size() != 1) { dictNProcs = roots.size()+1; } } else { source = rootPath_/globalCase_/"system/decomposeParDict"; IFstream decompDictStream(source); if (!decompDictStream.good()) { FatalError << "Cannot read " << decompDictStream.name() << exit(FatalError); } dictionary decompDict(decompDictStream); dictNProcs = readLabel ( decompDict.lookup("numberOfSubdomains") ); if (decompDict.lookupOrDefault("distributed", false)) { decompDict.lookup("roots") >> roots; } } // convenience: // when a single root is specified, use it for all processes if (roots.size() == 1) { const fileName rootName(roots[0]); roots.setSize(Pstream::nProcs()-1, rootName); // adjust dictNProcs for command-line '-roots' option if (dictNProcs < 0) { dictNProcs = roots.size()+1; } } // Check number of processors. // nProcs => number of actual procs // dictNProcs => number of procs specified in decompositionDict // nProcDirs => number of processor directories // (n/a when running distributed) // // - normal running : nProcs = dictNProcs = nProcDirs // - decomposition to more processors : nProcs = dictNProcs // - decomposition to fewer processors : nProcs = nProcDirs if (dictNProcs > Pstream::nProcs()) { FatalError << source << " specifies " << dictNProcs << " processors but job was started with " << Pstream::nProcs() << " processors." << exit(FatalError); } // distributed data if (roots.size()) { if (roots.size() != Pstream::nProcs()-1) { FatalError << "number of entries in roots " << roots.size() << " is not equal to the number of slaves " << Pstream::nProcs()-1 << exit(FatalError); } forAll(roots, i) { roots[i].expand(); } // Distribute the master's argument list (with new root) bool hadCaseOpt = options_.found("case"); for ( int slave = Pstream::firstSlave(); slave <= Pstream::lastSlave(); slave++ ) { options_.set("case", roots[slave-1]/globalCase_); OPstream toSlave(Pstream::scheduled, slave); toSlave << args_ << options_; } options_.erase("case"); // restore [-case dir] if (hadCaseOpt) { options_.set("case", rootPath_/globalCase_); } } else { // Possibly going to fewer processors. // Check if all procDirs are there. if (dictNProcs < Pstream::nProcs()) { label nProcDirs = 0; while ( isDir ( rootPath_/globalCase_/"processor" + name(++nProcDirs) ) ) {} if (nProcDirs != Pstream::nProcs()) { FatalError << "number of processor directories = " << nProcDirs << " is not equal to the number of processors = " << Pstream::nProcs() << exit(FatalError); } } // Distribute the master's argument list (unaltered) for ( int slave = Pstream::firstSlave(); slave <= Pstream::lastSlave(); slave++ ) { OPstream toSlave(Pstream::scheduled, slave); toSlave << args_ << options_; } } }
int doModify(int argc, char **argv, time_t newtimestamp) { char *name; int i, j, r; char *key, *val; FILE *f; struct bnl_record_hdr *crecord; if(argc < 1) { printUsage(argv0); return 1; } if(loadBNL() != 0) return 1; name = argv[0]; for(i = 0; i < numcurbnlrecords; i++) { if(strcasecmp(cur_bnlrecords[i]->name, name) == 0) break; } if(i == numcurbnlrecords) { fprintf(stderr, "No such name.\n"); return 1; } crecord = cur_bnlrecords[i]; for(i = 1; i < argc; i++) { if(strcasecmp(argv[i], "PreferIPv6") == 0) { crecord->addr6preferred = 1; continue; } if(strcasecmp(argv[i], "PreferIPv4") == 0 || strcasecmp(argv[i], "NoPreferIPv6") == 0) { crecord->addr6preferred = 0; continue; } key = argv[i]; val = strstr(argv[i], "="); if(!val) { printUsage(argv[0]); return 1; } *val = 0; val++; if(strcasecmp(key, "IPv4") == 0 || strcasecmp(key, "IP") == 0) { if(strlen(val) == 0) { crecord->addr4 = inaddr_none; } else { r = inet_pton(AF_INET, val, &crecord->addr4); if(r != 1) { fprintf(stderr, "Invalid IPv4 address\n"); return 1; } } continue; } if(strcasecmp(key, "IPv6") == 0) { if(strlen(val) == 0) { crecord->addr6 = in6addr_none; } else { r = inet_pton(AF_INET6, val, &crecord->addr6); if(r != 1) { fprintf(stderr, "Invalid IPv6 address\n"); return 1; } } continue; } if(strcasecmp(key, "Port") == 0) { if(strlen(val) == 0) { crecord->port = htons(3406); } else { crecord->port = htons(atoi(val)); } continue; } fprintf(stderr, "Invalid attribute\n"); return 1; } cur_bnlhdr->timestamp = htonl(newtimestamp); r = sig_signandmakefile(cur_bnldata, cur_bnldata_len, cur_bnlsigdata, &cur_bnlsigdata_len); if(r != SIG_OK) { fprintf(stderr, "Error signing file\n"); return 1; } f = fopen(bnl_filename, "w"); if(!f) { fprintf(stderr, "Error opening file\n"); return 1; } fwrite(cur_bnlsigdata, 1, cur_bnlsigdata_len, f); fclose(f); printf("Node %s modified.\n", name); return 0; }
int main (int argc, const char *argv[]) { int c; int ok; char *infile, *outfile; int fast, accurate; extern int optind; extern int optopt; extern char * optarg; if (argc < 4) { printUsage(); return(0); } // Provide default values. infile = outfile = NULL; fast = accurate = 1; // Process command line while (1) { static struct option long_options[] = { {"help", no_argument, 0, 'h'}, {"input", required_argument, 0, 'i'}, {"output", required_argument, 0, 'o'}, {"slower", no_argument, 0, 's'}, {"less_accurate", no_argument, 0, 'l'}, {0, 0, 0, 0} }; c = getopt_long(argc, (char**)argv, "hi:o:sl", long_options, NULL); if (c == -1) { break; } switch (c) { case 'h': printUsage(); return 0; case 'i': infile = optarg; break; case 'o': outfile = optarg; break; case 's': fast = 0; break; case 'l': accurate = 0; break; case '?': return 1; default: printUsage(); abort(); } } // Input value checking. if (infile == NULL) { fprintf(stderr, "Error. You must supply an input raster file.\n"); exit(1); } if (outfile == NULL) { fprintf(stderr, "Error. You must supply a path to an output morph file.\n"); exit(1); } printf("r.morph.equalize.density starting\n"); ok = equalize_density(infile, outfile, fast, accurate); printf("r.morph.equalize.density done\n"); return ok; }
int doAdd(int argc, char **argv, time_t newtimestamp) { struct bnl_record_hdr nrecord; int maxid = -1; int i, j, r; char *key, *val; struct bnl_record_subnet *subnets = NULL; int numsubnets = 0; struct bnl_record_subnet csub; char is6; char *newdata; int newdatalen; char *filebuf; unsigned int filelen; FILE *f; if(argc < 1) { printUsage(argv0); return 1; } if(loadBNL() != 0) return 1; memset(&nrecord, 0, sizeof(nrecord)); nrecord.port = htons(3406); strcpy(nrecord.name, argv[0]); for(i = 0; i < numcurbnlrecords; i++) { if((signed int)ntohl(cur_bnlrecords[i]->id) > maxid) { maxid = ntohl(cur_bnlrecords[i]->id); } } nrecord.id = htonl(maxid + 1); for(i = 1; i < argc; i++) { if(strcasecmp(argv[i], "PreferIPv6") == 0) { nrecord.addr6preferred = 1; continue; } key = argv[i]; val = strstr(argv[i], "="); if(!val) { printUsage(argv[0]); return 1; } *val = 0; val++; if(strcasecmp(key, "ID") == 0) { nrecord.id = htonl(atoi(val)); continue; } if(strcasecmp(key, "IPv4") == 0 || strcasecmp(key, "IP") == 0) { r = inet_pton(AF_INET, val, &nrecord.addr4); if(r != 1) { fprintf(stderr, "Invalid IPv4 address\n"); return 1; } continue; } if(strcasecmp(key, "IPv6") == 0) { r = inet_pton(AF_INET6, val, &nrecord.addr6); if(r != 1) { fprintf(stderr, "Invalid IPv6 address\n"); return 1; } continue; } if(strcasecmp(key, "Port") == 0) { nrecord.port = htons(atoi(val)); continue; } if(strcasecmp(key, "Subnet") == 0) { memset(&csub, 0, sizeof(csub)); is6 = 0; for(j = 0; j < strlen(val); j++) if(val[j] == ':') is6 = 1; for(j = 0; j < strlen(val); j++) if(val[j] == '/') { csub.cidr = atoi(val + j + 1); val[j] = 0; } csub.family = htons(is6 ? AF_INET6 : AF_INET); r = inet_pton(is6 ? AF_INET6 : AF_INET, val, &csub.addr); if(r != 1) { fprintf(stderr, "Invalid address\n"); return 1; } subnets = realloc(subnets, (numsubnets + 1) * sizeof(struct bnl_record_subnet)); subnets[numsubnets] = csub; numsubnets++; continue; } fprintf(stderr, "Invalid attribute\n"); return 1; } for(i = 0; i < numcurbnlrecords; i++) { if(cur_bnlrecords[i]->id == nrecord.id) { fprintf(stderr, "That ID already exists.\n"); return 1; } if(strcasecmp(cur_bnlrecords[i]->name, nrecord.name) == 0) { fprintf(stderr, "That name already exists.\n"); return 1; } } nrecord.numsubnets = htonl(numsubnets); newdatalen = cur_bnldata_len + sizeof(struct bnl_record_hdr) + sizeof(struct bnl_record_subnet) * numsubnets; newdata = malloc(newdatalen); memcpy(newdata, cur_bnldata, cur_bnldata_len); (*(struct bnl_header *)newdata).timestamp = htonl(newtimestamp); memcpy(newdata + cur_bnldata_len, &nrecord, sizeof(nrecord)); memcpy(newdata + cur_bnldata_len + sizeof(nrecord), subnets, numsubnets * sizeof(struct bnl_record_subnet)); filebuf = malloc(newdatalen + 1024); filelen = newdatalen + 1024; r = sig_signandmakefile(newdata, newdatalen, filebuf, &filelen); if(r != SIG_OK) { fprintf(stderr, "Error signing file\n"); return 1; } f = fopen(bnl_filename, "w"); if(!f) { fprintf(stderr, "Error opening file\n"); return 1; } fwrite(filebuf, 1, filelen, f); fclose(f); printf("Node %s added with ID %d.\n", nrecord.name, ntohl(nrecord.id)); return 0; }
extern int main(int argc, char *argv[]) { const char *pname, *sourcePath, *destPath, *inFilename, *outFilename, *outComment; char outType; UBool isHelp, isModified, isPackage; int result = 0; Package *pkg, *listPkg, *addListPkg; U_MAIN_INIT_ARGS(argc, argv); /* get the program basename */ pname=findBasename(argv[0]); argc=u_parseArgs(argc, argv, UPRV_LENGTHOF(options), options); isHelp=options[OPT_HELP_H].doesOccur || options[OPT_HELP_QUESTION_MARK].doesOccur; if(isHelp) { printUsage(pname, TRUE); return U_ZERO_ERROR; } pkg=new Package; if(pkg==NULL) { fprintf(stderr, "icupkg: not enough memory\n"); return U_MEMORY_ALLOCATION_ERROR; } isModified=FALSE; int autoPrefix=0; if(options[OPT_AUTO_TOC_PREFIX].doesOccur) { pkg->setAutoPrefix(); ++autoPrefix; } if(options[OPT_AUTO_TOC_PREFIX_WITH_TYPE].doesOccur) { if(options[OPT_TOC_PREFIX].doesOccur) { fprintf(stderr, "icupkg: --auto_toc_prefix_with_type and also --toc_prefix\n"); printUsage(pname, FALSE); return U_ILLEGAL_ARGUMENT_ERROR; } pkg->setAutoPrefixWithType(); ++autoPrefix; } if(argc<2 || 3<argc || autoPrefix>1) { printUsage(pname, FALSE); return U_ILLEGAL_ARGUMENT_ERROR; } if(options[OPT_SOURCEDIR].doesOccur) { sourcePath=options[OPT_SOURCEDIR].value; } else { // work relative to the current working directory sourcePath=NULL; } if(options[OPT_DESTDIR].doesOccur) { destPath=options[OPT_DESTDIR].value; } else { // work relative to the current working directory destPath=NULL; } if(0==strcmp(argv[1], "new")) { if(autoPrefix) { fprintf(stderr, "icupkg: --auto_toc_prefix[_with_type] but no input package\n"); printUsage(pname, FALSE); return U_ILLEGAL_ARGUMENT_ERROR; } inFilename=NULL; isPackage=TRUE; } else { inFilename=argv[1]; if(isPackageName(inFilename)) { pkg->readPackage(inFilename); isPackage=TRUE; } else { /* swap a single file (icuswap replacement) rather than work on a package */ pkg->addFile(sourcePath, inFilename); isPackage=FALSE; } } if(argc>=3) { outFilename=argv[2]; if(0!=strcmp(argv[1], argv[2])) { isModified=TRUE; } } else if(isPackage) { outFilename=NULL; } else { /* !isPackage */ outFilename=inFilename; isModified=(UBool)(sourcePath!=destPath); } /* parse the output type option */ if(options[OPT_OUT_TYPE].doesOccur) { const char *type=options[OPT_OUT_TYPE].value; if(type[0]==0 || type[1]!=0) { /* the type must be exactly one letter */ printUsage(pname, FALSE); return U_ILLEGAL_ARGUMENT_ERROR; } outType=type[0]; switch(outType) { case 'l': case 'b': case 'e': break; default: printUsage(pname, FALSE); return U_ILLEGAL_ARGUMENT_ERROR; } /* * Set the isModified flag if the output type differs from the * input package type. * If we swap a single file, just assume that we are modifying it. * The Package class does not give us access to the item and its type. */ isModified|=(UBool)(!isPackage || outType!=pkg->getInType()); } else if(isPackage) { outType=pkg->getInType(); // default to input type } else { /* !isPackage: swap single file */ outType=0; /* tells extractItem() to not swap */ } if(options[OPT_WRITEPKG].doesOccur) { isModified=TRUE; } if(!isPackage) { /* * icuswap tool replacement: Only swap a single file. * Check that irrelevant options are not set. */ if( options[OPT_COMMENT].doesOccur || options[OPT_COPYRIGHT].doesOccur || options[OPT_MATCHMODE].doesOccur || options[OPT_REMOVE_LIST].doesOccur || options[OPT_ADD_LIST].doesOccur || options[OPT_EXTRACT_LIST].doesOccur || options[OPT_LIST_ITEMS].doesOccur ) { printUsage(pname, FALSE); return U_ILLEGAL_ARGUMENT_ERROR; } if(isModified) { pkg->extractItem(destPath, outFilename, 0, outType); } delete pkg; return result; } /* Work with a package. */ if(options[OPT_COMMENT].doesOccur) { outComment=options[OPT_COMMENT].value; } else if(options[OPT_COPYRIGHT].doesOccur) { outComment=U_COPYRIGHT_STRING; } else { outComment=NULL; } if(options[OPT_MATCHMODE].doesOccur) { if(0==strcmp(options[OPT_MATCHMODE].value, "noslash")) { pkg->setMatchMode(Package::MATCH_NOSLASH); } else { printUsage(pname, FALSE); return U_ILLEGAL_ARGUMENT_ERROR; } } /* remove items */ if(options[OPT_REMOVE_LIST].doesOccur) { listPkg=new Package(); if(listPkg==NULL) { fprintf(stderr, "icupkg: not enough memory\n"); exit(U_MEMORY_ALLOCATION_ERROR); } if(readList(NULL, options[OPT_REMOVE_LIST].value, FALSE, listPkg)) { pkg->removeItems(*listPkg); delete listPkg; isModified=TRUE; } else { printUsage(pname, FALSE); return U_ILLEGAL_ARGUMENT_ERROR; } } /* * add items * use a separate Package so that its memory and items stay around * as long as the main Package */ addListPkg=NULL; if(options[OPT_ADD_LIST].doesOccur) { addListPkg=new Package(); if(addListPkg==NULL) { fprintf(stderr, "icupkg: not enough memory\n"); exit(U_MEMORY_ALLOCATION_ERROR); } if(readList(sourcePath, options[OPT_ADD_LIST].value, TRUE, addListPkg)) { pkg->addItems(*addListPkg); // delete addListPkg; deferred until after writePackage() isModified=TRUE; } else { printUsage(pname, FALSE); return U_ILLEGAL_ARGUMENT_ERROR; } } /* extract items */ if(options[OPT_EXTRACT_LIST].doesOccur) { listPkg=new Package(); if(listPkg==NULL) { fprintf(stderr, "icupkg: not enough memory\n"); exit(U_MEMORY_ALLOCATION_ERROR); } if(readList(NULL, options[OPT_EXTRACT_LIST].value, FALSE, listPkg)) { pkg->extractItems(destPath, *listPkg, outType); delete listPkg; } else { printUsage(pname, FALSE); return U_ILLEGAL_ARGUMENT_ERROR; } } /* list items */ if(options[OPT_LIST_ITEMS].doesOccur) { int32_t i; if (options[OPT_LIST_FILE].doesOccur) { FileStream *out; out = T_FileStream_open(options[OPT_LIST_FILE].value, "w"); if (out != NULL) { for(i=0; i<pkg->getItemCount(); ++i) { T_FileStream_writeLine(out, pkg->getItem(i)->name); T_FileStream_writeLine(out, "\n"); } T_FileStream_close(out); } else { return U_ILLEGAL_ARGUMENT_ERROR; } } else { for(i=0; i<pkg->getItemCount(); ++i) { fprintf(stdout, "%s\n", pkg->getItem(i)->name); } } } /* check dependencies between items */ if(!pkg->checkDependencies()) { /* some dependencies are not fulfilled */ return U_MISSING_RESOURCE_ERROR; } /* write the output .dat package if there are any modifications */ if(isModified) { char outFilenameBuffer[1024]; // for auto-generated output filename, if necessary if(outFilename==NULL || outFilename[0]==0) { if(inFilename==NULL || inFilename[0]==0) { fprintf(stderr, "icupkg: unable to auto-generate an output filename if there is no input filename\n"); exit(U_ILLEGAL_ARGUMENT_ERROR); } /* * auto-generate a filename: * copy the inFilename, * and if the last basename character matches the input file's type, * then replace it with the output file's type */ char suffix[6]="?.dat"; char *s; suffix[0]=pkg->getInType(); strcpy(outFilenameBuffer, inFilename); s=strchr(outFilenameBuffer, 0); if((s-outFilenameBuffer)>5 && 0==memcmp(s-5, suffix, 5)) { *(s-5)=outType; } outFilename=outFilenameBuffer; } if(options[OPT_TOC_PREFIX].doesOccur) { pkg->setPrefix(options[OPT_TOC_PREFIX].value); } result = writePackageDatFile(outFilename, outComment, NULL, NULL, pkg, outType); } delete addListPkg; delete pkg; return result; }
int main(int argc, char **argv) { char *optstring = "c:t:b:"; int copt; char bnlspecified = 0; int r; char *rptr; newtimestamp = time(NULL); argv0 = argv[0]; if(argc < 2) { printUsage(argv[0]); return 1; } for(;;) { copt = getopt(argc, argv, optstring); if(copt == -1) break; if(copt == '?') { fprintf(stderr, "Invalid option."); return 1; } switch(copt) { case 'c': strcpy(configfile_dir, optarg); break; case 't': newtimestamp = atoi(optarg); break; case 'b': strcpy(bnl_filename, optarg); bnlspecified = 1; break; } } // Get orig directory rptr = getcwd(configfile_origdir, CONFIGFILE_FILENAME_LEN); // cd to the new directory r = chdir(configfile_dir); if(r != 0) { fprintf(stderr, "Error changing to configfile dir"); return 1; } // Load config file if(configfile_load() != CONFIGFILE_OK) { fprintf(stderr, "Error loading config file.\n"); return 1; } // Load SSL error strings SSL_load_error_strings(); // Initialize signatures if(sig_init() != SIG_OK) { fprintf(stderr, "Error initializing signatures.\n"); return 1; } // Command if(argc - optind < 1) { printUsage(argv[0]); return 1; } if(bnlspecified) r = chdir(configfile_origdir); if(strcmp(argv[optind], "print") == 0) { if(argc - optind != 1) { printUsage(argv[0]); return 1; } return doPrintBNL(); } if(strcmp(argv[optind], "new") == 0) { if(argc - optind != 1) { printUsage(argv[0]); return 1; } return doNew(newtimestamp); } if(strcmp(argv[optind], "add") == 0) { return doAdd(argc - optind - 1, &argv[optind + 1], newtimestamp); } if(strcmp(argv[optind], "modify") == 0) { return doModify(argc - optind - 1, &argv[optind + 1], newtimestamp); } if(strcmp(argv[optind], "remove") == 0) { if(argc - optind != 2) { printUsage(argv[0]); return 1; } return doRemove(argv[optind + 1], newtimestamp); } if(strcmp(argv[optind], "addsubnet") == 0) { if(argc - optind != 3) { printUsage(argv[0]); return 1; } return doAddSubnet(argv[optind + 1], argv[optind + 2], newtimestamp); } if(strcmp(argv[optind], "delsubnet") == 0) { if(argc - optind != 3) { printUsage(argv[0]); return 1; } return doDelSubnet(argv[optind + 1], argv[optind + 2], newtimestamp); } printUsage(argv[0]); return 1; }
int main(int argc, char** argv){ char *message_1 = "The use of COBOL cripples the mind; its " "teaching should, therefore, be regarded as a criminal " "offense. -- Edsgar Dijkstra"; char *message_2 = "C makes it easy to shoot yourself in the " "foot; C++ makes it harder, but when you do, it blows away " "your whole leg. -- Bjarne Stroustrup"; char *message_3 = "A mathematician is a device for turning " "coffee into theorems. -- Paul Erdos"; char *message_4 = "Grove giveth and Gates taketh away. " "-- Bob Metcalfe (inventor of Ethernet) on the trend of " "hardware speedups not being able to keep up with software demands"; char *message_5 = "Wise men make proverbs, but fools repeat them. " "-- Samuel Palmer (1805-80)"; char *rcv_buffer; int length; RTP_CONNECTION *connection; if (argc < 3){ printUsage(); return EXIT_FAILURE; } if ((connection = rtp_connect(argv[1],atoi(argv[2]))) == NULL){ printUsage(); return EXIT_FAILURE; } printf("Sending quotes to a remote host to have them " "converted to pig latin!\n\n"); rtp_send_message(connection,message_1,strlen(message_1)+1); rtp_recv_message(connection,&rcv_buffer,&length); if (rcv_buffer == NULL){ printf("Connection reset by peer.\n"); return EXIT_FAILURE; } printf("%s\n\n",rcv_buffer); free(rcv_buffer); rtp_send_message(connection,message_2,strlen(message_2)+1); rtp_recv_message(connection,&rcv_buffer,&length); if (rcv_buffer == NULL){ printf("Connection reset by peer.\n"); return EXIT_FAILURE; } printf("%s\n\n",rcv_buffer); free(rcv_buffer); rtp_send_message(connection,message_3,strlen(message_3)+1); rtp_recv_message(connection,&rcv_buffer,&length); if (rcv_buffer == NULL){ printf("Connection reset by peer.\n"); return EXIT_FAILURE; } printf("%s\n\n",rcv_buffer); free(rcv_buffer); rtp_send_message(connection,message_4,strlen(message_4)+1); rtp_recv_message(connection,&rcv_buffer,&length); if (rcv_buffer == NULL){ printf("Connection reset by peer.\n"); return EXIT_FAILURE; } printf("%s\n\n",rcv_buffer); free(rcv_buffer); rtp_send_message(connection,message_5,strlen(message_5)+1); rtp_recv_message(connection,&rcv_buffer,&length); if (rcv_buffer == NULL){ printf("Connection reset by peer.\n"); return EXIT_FAILURE; } printf("%s\n\n",rcv_buffer); free(rcv_buffer); rtp_disconnect(connection); return EXIT_SUCCESS; }
int main(int argc, char *argv[]) { extern char *optarg; extern int optind; int opt; SVDRec R = NULL; SMat A = NULL; char transpose = FALSE; int readFormat = SVD_F_ST; int writeFormat = SVD_F_DT; int algorithm = LAS2; int iterations = 0; int dimensions = 0; char *vectorFile = NULL; double las2end[2] = {-1.0e-30, 1.0e-30}; double kappa = 1e-6; double exetime; while ((opt = getopt(argc, argv, "a:c:d:e:hk:i:o:r:tv:w:")) != -1) { switch (opt) { case 'a': if (!strcasecmp(optarg, "las2")) algorithm = LAS2; else fatalError("unknown algorithm: %s", optarg); break; case 'c': if (optind != argc - 1) printUsage(argv[0]); if (SVDVerbosity > 0) printf("Converting %s to %s\n", optarg, argv[optind]); if (SVD_IS_SPARSE(readFormat) && SVD_IS_SPARSE(writeFormat)) { SMat S = svdLoadSparseMatrix(optarg, readFormat); if (!S) fatalError("failed to read sparse matrix"); if (transpose) { if (SVDVerbosity > 0) printf(" Transposing the matrix...\n"); S = svdTransposeS(S); /* This leaks memory. */ } svdWriteSparseMatrix(S, argv[optind], writeFormat); } else { DMat D = svdLoadDenseMatrix(optarg, readFormat); if (!D) fatalError("failed to read dense matrix"); if (transpose) { if (SVDVerbosity > 0) printf(" Transposing the matrix...\n"); D = svdTransposeD(D); /* This leaks memory. */ } svdWriteDenseMatrix(D, argv[optind], writeFormat); } exit(0); break; case 'd': dimensions = atoi(optarg); if (dimensions < 0) fatalError("dimensions must be non-negative"); break; case 'e': las2end[1] = atof(optarg); las2end[0] = -las2end[1]; break; case 'h': printUsage(argv[0]); break; case 'k': kappa = atof(optarg); break; case 'i': iterations = atoi(optarg); break; case 'o': vectorFile = optarg; break; case 'r': if (!strcasecmp(optarg, "sth")) { readFormat = SVD_F_STH; } else if (!strcasecmp(optarg, "st")) { readFormat = SVD_F_ST; } else if (!strcasecmp(optarg, "dt")) { readFormat = SVD_F_DT; } else if (!strcasecmp(optarg, "sb")) { readFormat = SVD_F_SB; } else if (!strcasecmp(optarg, "db")) { readFormat = SVD_F_DB; } else fatalError("bad file format: %s", optarg); break; case 't': transpose = TRUE; break; case 'v': SVDVerbosity = atoi(optarg); /*if (SVDVerbosity) printf("Verbosity = %ld\n", SVDVerbosity);*/ break; case 'w': if (!strcasecmp(optarg, "sth")) { writeFormat = SVD_F_STH; } else if (!strcasecmp(optarg, "st")) { writeFormat = SVD_F_ST; } else if (!strcasecmp(optarg, "dt")) { writeFormat = SVD_F_DT; } else if (!strcasecmp(optarg, "sb")) { writeFormat = SVD_F_SB; } else if (!strcasecmp(optarg, "db")) { writeFormat = SVD_F_DB; } else fatalError("bad file format: %s", optarg); break; default: printUsage(argv[0]); } } if (optind != argc - 1) printUsage(argv[0]); if (SVDVerbosity > 0) printf("Loading the matrix...\n"); A = svdLoadSparseMatrix(argv[optind], readFormat); if (!A) fatalError("failed to read sparse matrix. Did you specify the correct file type with the -r argument?"); if (transpose) { if (SVDVerbosity > 0) printf(" Transposing the matrix...\n"); SMat T = A; A = svdTransposeS(A); svdFreeSMat(T); } if (dimensions <= 0) dimensions = imin(A->rows, A->cols); exetime = timer(); if (SVDVerbosity > 0) printf("Computing the SVD...\n"); if (algorithm == LAS2) { if (!(R = svdLAS2(A, dimensions, iterations, las2end, kappa))) fatalError("error in svdLAS2"); } else { fatalError("unknown algorithm"); } exetime = timer() - exetime; if (SVDVerbosity > 0) { printf("\nELAPSED CPU TIME = %6g sec.\n", exetime); printf("MULTIPLICATIONS BY A = %6ld\n", (SVDCount[SVD_MXV] - R->d) / 2 + R->d); printf("MULTIPLICATIONS BY A^T = %6ld\n", (SVDCount[SVD_MXV] - R->d) / 2); } if (vectorFile) { char filename[128]; sprintf(filename, "%s-Ut", vectorFile); svdWriteDenseMatrix(R->Ut, filename, writeFormat); sprintf(filename, "%s-S", vectorFile); svdWriteDenseArray(R->S, R->d, filename, FALSE); sprintf(filename, "%s-Vt", vectorFile); svdWriteDenseMatrix(R->Vt, filename, writeFormat); } return 0; }
int main (int argc, char *argv[]) { char *socketPath = "/tmp/CO_command_socket"; /* Name of the local domain socket, configurable by arguments. */ char *inputFilePath = NULL; char buf[BUF_SIZE]; int fd; struct sockaddr_un addr; int opt; int i; if(argc >= 2 && strcmp(argv[1], "--help") == 0) { printUsage(argv[0]); exit(EXIT_SUCCESS); } if(argc >= 2 && strcmp(argv[1], "--helpall") == 0) { printUsage(argv[0]); printErrorDescs(); exit(EXIT_SUCCESS); } /* Get program options */ while((opt = getopt(argc, argv, "s:f:h")) != -1) { switch (opt) { case 'f': inputFilePath = optarg; break; case 's': socketPath = optarg; break; case 'h': printErrorDescription = 1; break; default: printUsage(argv[0]); exit(EXIT_FAILURE); } } /* Create and connect client socket */ fd = socket(AF_UNIX, SOCK_STREAM, 0); if(fd == -1) { errExit("Socket creation failed"); } memset(&addr, 0, sizeof(struct sockaddr_un)); addr.sun_family = AF_UNIX; strncpy(addr.sun_path, socketPath, sizeof(addr.sun_path) - 1); if(connect(fd, (struct sockaddr *)&addr, sizeof(struct sockaddr_un)) == -1) { errExit("Socket connection failed"); } /* get commands from input file, line after line */ if(inputFilePath != NULL) { FILE *fp = fopen(inputFilePath, "r"); if(fp == NULL) { errExit("Can't open input file"); } while(fgets(buf, BUF_SIZE, fp) != NULL) { sendCommand(fd, buf, strlen(buf)); } fclose(fp); } /* get command from arguments */ else if(optind < argc) { buf[0] = 0; size_t buflen = 0; /* Add sequence number if not present on command line arguments */ if(argv[optind][0] != '[') { strcat(buf, "[1] "); } for(i=optind; i<argc; i++) { strncat(buf, argv[i], (BUF_SIZE - 2) - buflen); strcat(buf, " "); buflen = strlen(buf); if(buflen >= (BUF_SIZE - 1)) { fprintf(stderr, "String too long!\n"); exit(EXIT_FAILURE); } } buf[buflen - 1] = '\n'; /* replace last space with newline */ printErrorDescription = 1; sendCommand(fd, buf, buflen); } /* get commands from stdin, line after line */ else { while(fgets(buf, BUF_SIZE, stdin) != NULL) { sendCommand(fd, buf, strlen(buf)); } } close(fd); exit(EXIT_SUCCESS); }
int main(int argc, const char ** argv) #endif /*@globals rpmEVR, RPMVERSION, rpmGlobalMacroContext, rpmCLIMacroContext, h_errno, fileSystem, internalState@*/ /*@modifies fileSystem, internalState@*/ { poptContext optCon = rpmcliInit(argc, (char *const *)argv, optionsTable); rpmts ts = NULL; enum modes bigMode = MODE_UNKNOWN; #if defined(IAM_RPMQV) QVA_t qva = &rpmQVKArgs; #endif #ifdef IAM_RPMBT BTA_t ba = &rpmBTArgs; #endif #ifdef IAM_RPMEIU QVA_t ia = &rpmIArgs; #endif #if defined(IAM_RPMDB) QVA_t da = &rpmDBArgs; #endif #if defined(IAM_RPMK) QVA_t ka = &rpmQVKArgs; #endif #if defined(IAM_RPMBT) || defined(IAM_RPMK) char * passPhrase = ""; #endif pid_t pipeChild = 0; int ec = 0; int status; int p[2]; #ifdef IAM_RPMEIU int xx; #endif #if !defined(__GLIBC__) && !defined(__LCLINT__) environ = envp; #else /* XXX limit the fiddle up to linux for now. */ #if !defined(HAVE_SETPROCTITLE) && defined(__linux__) (void) initproctitle(argc, (char **)argv, environ); #endif #endif /* Set the major mode based on argv[0] */ /*@-nullpass@*/ #ifdef IAM_RPMBT if (!strcmp(__progname, "rpmb")) bigMode = MODE_BUILD; if (!strcmp(__progname, "lt-rpmb")) bigMode = MODE_BUILD; if (!strcmp(__progname, "rpmt")) bigMode = MODE_TARBUILD; if (!strcmp(__progname, "rpmbuild")) bigMode = MODE_BUILD; #endif #ifdef IAM_RPMQV if (!strcmp(__progname, "rpmq")) bigMode = MODE_QUERY; if (!strcmp(__progname, "lt-rpmq")) bigMode = MODE_QUERY; if (!strcmp(__progname, "rpmv")) bigMode = MODE_VERIFY; if (!strcmp(__progname, "rpmquery")) bigMode = MODE_QUERY; if (!strcmp(__progname, "rpmverify")) bigMode = MODE_VERIFY; #endif #ifdef RPMEIU if (!strcmp(__progname, "rpme")) bigMode = MODE_ERASE; if (!strcmp(__progname, "rpmi")) bigMode = MODE_INSTALL; if (!strcmp(__progname, "lt-rpmi")) bigMode = MODE_INSTALL; if (!strcmp(__progname, "rpmu")) bigMode = MODE_INSTALL; #endif /*@=nullpass@*/ #if defined(IAM_RPMQV) /* Jumpstart option from argv[0] if necessary. */ switch (bigMode) { case MODE_QUERY: qva->qva_mode = 'q'; break; case MODE_VERIFY: qva->qva_mode = 'V'; break; case MODE_CHECKSIG: qva->qva_mode = 'K'; break; case MODE_RESIGN: qva->qva_mode = 'R'; break; case MODE_INSTALL: case MODE_ERASE: case MODE_BUILD: case MODE_REBUILD: case MODE_RECOMPILE: case MODE_TARBUILD: case MODE_REBUILDDB: case MODE_UNKNOWN: default: break; } #endif rpmcliConfigured(); #ifdef IAM_RPMBT switch (ba->buildMode) { case 'b': bigMode = MODE_BUILD; break; case 't': bigMode = MODE_TARBUILD; break; case 'B': bigMode = MODE_REBUILD; break; case 'C': bigMode = MODE_RECOMPILE; break; } if ((ba->buildAmount & RPMBUILD_RMSOURCE) && bigMode == MODE_UNKNOWN) bigMode = MODE_BUILD; if ((ba->buildAmount & RPMBUILD_RMSPEC) && bigMode == MODE_UNKNOWN) bigMode = MODE_BUILD; #endif /* IAM_RPMBT */ #ifdef IAM_RPMDB if (bigMode == MODE_UNKNOWN || (bigMode & MODES_DB)) { if (da->rebuild) { if (bigMode != MODE_UNKNOWN) argerror(_("only one major mode may be specified")); else bigMode = MODE_REBUILDDB; } } #endif /* IAM_RPMDB */ #ifdef IAM_RPMQV if (bigMode == MODE_UNKNOWN || (bigMode & MODES_QV)) { switch (qva->qva_mode) { case 'q': bigMode = MODE_QUERY; break; case 'V': bigMode = MODE_VERIFY; break; } if (qva->qva_sourceCount) { if (qva->qva_sourceCount > 2) argerror(_("one type of query/verify may be performed at a " "time")); } if (qva->qva_flags && (bigMode & ~MODES_QV)) argerror(_("unexpected query flags")); if (qva->qva_queryFormat && (bigMode & ~MODES_QV)) argerror(_("unexpected query format")); if (qva->qva_source != RPMQV_PACKAGE && (bigMode & ~MODES_QV)) argerror(_("unexpected query source")); } #endif /* IAM_RPMQV */ #ifdef IAM_RPMEIU if (bigMode == MODE_UNKNOWN || (bigMode & MODES_IE)) { int iflags = (ia->installInterfaceFlags & (INSTALL_UPGRADE|INSTALL_FRESHEN|INSTALL_INSTALL)); int eflags = (ia->installInterfaceFlags & INSTALL_ERASE); if (iflags & eflags) argerror(_("only one major mode may be specified")); else if (iflags) bigMode = MODE_INSTALL; else if (eflags) bigMode = MODE_ERASE; } #endif /* IAM_RPMEIU */ #ifdef IAM_RPMK if (bigMode == MODE_UNKNOWN || (bigMode & MODES_K)) { switch (ka->qva_mode) { case RPMSIGN_NONE: ka->sign = 0; break; case RPMSIGN_IMPORT_PUBKEY: case RPMSIGN_CHK_SIGNATURE: bigMode = MODE_CHECKSIG; ka->sign = 0; break; case RPMSIGN_ADD_SIGNATURE: case RPMSIGN_NEW_SIGNATURE: case RPMSIGN_DEL_SIGNATURE: bigMode = MODE_RESIGN; ka->sign = (ka->qva_mode != RPMSIGN_DEL_SIGNATURE); break; } } #endif /* IAM_RPMK */ #if defined(IAM_RPMEIU) if (!( bigMode == MODE_INSTALL ) && (ia->probFilter & (RPMPROB_FILTER_REPLACEPKG | RPMPROB_FILTER_OLDPACKAGE))) argerror(_("only installation, upgrading, rmsource and rmspec may be forced")); if (bigMode != MODE_INSTALL && (ia->probFilter & RPMPROB_FILTER_FORCERELOCATE)) argerror(_("files may only be relocated during package installation")); if (ia->relocations && ia->qva_prefix) argerror(_("cannot use --prefix with --relocate or --excludepath")); if (bigMode != MODE_INSTALL && ia->relocations) argerror(_("--relocate and --excludepath may only be used when installing new packages")); if (bigMode != MODE_INSTALL && ia->qva_prefix) argerror(_("--prefix may only be used when installing new packages")); if (ia->qva_prefix && ia->qva_prefix[0] != '/') argerror(_("arguments to --prefix must begin with a /")); if (bigMode != MODE_INSTALL && (ia->installInterfaceFlags & INSTALL_HASH)) argerror(_("--hash (-h) may only be specified during package " "installation")); if (bigMode != MODE_INSTALL && (ia->installInterfaceFlags & INSTALL_PERCENT)) argerror(_("--percent may only be specified during package " "installation")); if (bigMode != MODE_INSTALL && (ia->probFilter & RPMPROB_FILTER_REPLACEPKG)) argerror(_("--replacepkgs may only be specified during package " "installation")); if (bigMode != MODE_INSTALL && (ia->transFlags & RPMTRANS_FLAG_NODOCS)) argerror(_("--excludedocs may only be specified during package " "installation")); if (bigMode != MODE_INSTALL && ia->incldocs) argerror(_("--includedocs may only be specified during package " "installation")); if (ia->incldocs && (ia->transFlags & RPMTRANS_FLAG_NODOCS)) argerror(_("only one of --excludedocs and --includedocs may be " "specified")); if (bigMode != MODE_INSTALL && (ia->probFilter & RPMPROB_FILTER_IGNOREARCH)) argerror(_("--ignorearch may only be specified during package " "installation")); if (bigMode != MODE_INSTALL && (ia->probFilter & RPMPROB_FILTER_IGNOREOS)) argerror(_("--ignoreos may only be specified during package " "installation")); if ((ia->installInterfaceFlags & INSTALL_ALLMATCHES) && bigMode != MODE_ERASE) argerror(_("--allmatches may only be specified during package " "erasure")); if ((ia->transFlags & RPMTRANS_FLAG_ALLFILES) && bigMode != MODE_INSTALL) argerror(_("--allfiles may only be specified during package " "installation")); if ((ia->transFlags & RPMTRANS_FLAG_JUSTDB) && bigMode != MODE_INSTALL && bigMode != MODE_ERASE) argerror(_("--justdb may only be specified during package " "installation and erasure")); if (bigMode != MODE_INSTALL && bigMode != MODE_ERASE && (ia->transFlags & (RPMTRANS_FLAG_NOSCRIPTS | _noTransScripts | _noTransTriggers))) argerror(_("script disabling options may only be specified during " "package installation and erasure")); if (bigMode != MODE_INSTALL && bigMode != MODE_ERASE && (ia->transFlags & (RPMTRANS_FLAG_NOTRIGGERS | _noTransTriggers))) argerror(_("trigger disabling options may only be specified during " "package installation and erasure")); if (ia->noDeps & (bigMode & ~MODES_FOR_NODEPS)) argerror(_("--nodeps may only be specified during package " "building, rebuilding, recompilation, installation, " "erasure, and verification")); if ((ia->transFlags & RPMTRANS_FLAG_TEST) && (bigMode & ~MODES_FOR_TEST)) argerror(_("--test may only be specified during package installation, " "erasure, and building")); #endif /* IAM_RPMEIU */ if (rpmioRootDir && rpmioRootDir[1] && (bigMode & ~MODES_FOR_ROOT)) argerror(_("--root (-r) may only be specified during " "installation, erasure, querying, and " "database rebuilds")); if (rpmioRootDir) { switch (urlIsURL(rpmioRootDir)) { default: if (bigMode & MODES_FOR_ROOT) break; /*@fallthrough@*/ case URL_IS_UNKNOWN: if (rpmioRootDir[0] != '/') argerror(_("arguments to --root (-r) must begin with a /")); break; } } #if defined(RPM_VENDOR_OPENPKG) /* integrity-checking */ integrity_check(__progname, bigMode); #endif #if defined(IAM_RPMBT) || defined(IAM_RPMK) if (0 #if defined(IAM_RPMBT) || ba->sign #endif #if defined(IAM_RPMK) || ka->sign #endif ) /*@-branchstate@*/ { if (bigMode == MODE_REBUILD || bigMode == MODE_BUILD || bigMode == MODE_RESIGN || bigMode == MODE_TARBUILD) { const char ** av; struct stat sb; int errors = 0; if ((av = poptGetArgs(optCon)) == NULL) { fprintf(stderr, _("no files to sign\n")); errors++; } else while (*av) { if (Stat(*av, &sb)) { fprintf(stderr, _("cannot access file %s\n"), *av); errors++; } av++; } if (errors) { ec = errors; goto exit; } if (poptPeekArg(optCon) #if defined(IAM_RPMBT) && !ba->nopassword #endif #if defined(IAM_RPMK) && !ka->nopassword #endif ) { passPhrase = Getpass(_("Enter pass phrase: ")); if (rpmCheckPassPhrase(passPhrase)) { fprintf(stderr, _("Pass phrase check failed\n")); ec = EXIT_FAILURE; goto exit; } fprintf(stderr, _("Pass phrase is good.\n")); /* XXX Getpass() should realloc instead. */ passPhrase = xstrdup(passPhrase); } } } /*@=branchstate@*/ #endif /* IAM_RPMBT || IAM_RPMK */ if (rpmioPipeOutput) { if (pipe(p) < 0) { fprintf(stderr, _("creating a pipe for --pipe failed: %m\n")); goto exit; } if (!(pipeChild = fork())) { (void) close(p[1]); (void) dup2(p[0], STDIN_FILENO); (void) close(p[0]); (void) execl("/bin/sh", "/bin/sh", "-c", rpmioPipeOutput, NULL); fprintf(stderr, _("exec failed\n")); } (void) close(p[0]); (void) dup2(p[1], STDOUT_FILENO); (void) close(p[1]); } ts = rpmtsCreate(); (void) rpmtsSetRootDir(ts, rpmioRootDir); switch (bigMode) { #ifdef IAM_RPMDB case MODE_REBUILDDB: { rpmVSFlags vsflags = rpmExpandNumeric("%{_vsflags_rebuilddb}"); rpmVSFlags ovsflags; if (rpmcliQueryFlags & VERIFY_DIGEST) vsflags |= _RPMVSF_NODIGESTS; if (rpmcliQueryFlags & VERIFY_SIGNATURE) vsflags |= _RPMVSF_NOSIGNATURES; ovsflags = rpmtsSetVSFlags(ts, vsflags); ec = rpmtsRebuildDB(ts); vsflags = rpmtsSetVSFlags(ts, ovsflags); } break; #endif /* IAM_RPMDB */ #ifdef IAM_RPMBT case MODE_REBUILD: case MODE_RECOMPILE: { const char * pkg; int nbuilds = 0; while (!rpmIsVerbose()) rpmIncreaseVerbosity(); if (!poptPeekArg(optCon)) argerror(_("no packages files given for rebuild")); ba->buildAmount = RPMBUILD_PREP | RPMBUILD_BUILD | RPMBUILD_INSTALL | RPMBUILD_CHECK; if (bigMode == MODE_REBUILD) { ba->buildAmount |= RPMBUILD_PACKAGEBINARY; ba->buildAmount |= RPMBUILD_RMSOURCE; ba->buildAmount |= RPMBUILD_RMSPEC; ba->buildAmount |= RPMBUILD_CLEAN; ba->buildAmount |= RPMBUILD_RMBUILD; } while ((pkg = poptGetArg(optCon))) { if (nbuilds++ > 0) { rpmFreeMacros(NULL); rpmFreeRpmrc(); (void) rpmReadConfigFiles(NULL, NULL); } ba->specFile = NULL; ba->cookie = NULL; ec = rpmInstallSource(ts, pkg, &ba->specFile, &ba->cookie); if (ec == 0) { ba->rootdir = rpmioRootDir; ba->passPhrase = passPhrase; ec = build(ts, ba, NULL); } ba->cookie = _free(ba->cookie); ba->specFile = _free(ba->specFile); if (ec) /*@loopbreak@*/ break; } } break; case MODE_BUILD: case MODE_TARBUILD: { int nbuilds = 0; #if defined(RPM_VENDOR_OPENPKG) /* no-auto-verbose-increase-for-track-and-fetch */ if (ba->buildChar != 't' && ba->buildChar != 'f') #endif while (!rpmIsVerbose()) rpmIncreaseVerbosity(); switch (ba->buildChar) { case 'a': ba->buildAmount |= RPMBUILD_PACKAGESOURCE; /*@fallthrough@*/ case 'b': ba->buildAmount |= RPMBUILD_PACKAGEBINARY; ba->buildAmount |= RPMBUILD_CLEAN; if ((ba->buildChar == 'b') && ba->shortCircuit) /*@innerbreak@*/ break; /*@fallthrough@*/ case 'i': ba->buildAmount |= RPMBUILD_INSTALL; ba->buildAmount |= RPMBUILD_CHECK; if ((ba->buildChar == 'i') && ba->shortCircuit) /*@innerbreak@*/ break; /*@fallthrough@*/ case 'c': ba->buildAmount |= RPMBUILD_BUILD; if ((ba->buildChar == 'c') && ba->shortCircuit) /*@innerbreak@*/ break; /*@fallthrough@*/ case 'p': ba->buildAmount |= RPMBUILD_PREP; /*@innerbreak@*/ break; case 'l': ba->buildAmount |= RPMBUILD_FILECHECK; /*@innerbreak@*/ break; case 's': ba->buildAmount |= RPMBUILD_PACKAGESOURCE; #if defined(RPM_VENDOR_OPENPKG) || defined(RPM_VENDOR_MANDRIVA) || defined(RPM_VENDOR_ARK) /* no-deps-on-building-srpms */ /* enforce no dependency checking when rolling a source RPM */ ba->noDeps = 1; #endif /*@innerbreak@*/ break; case 't': /* support extracting the "%track" script/section */ ba->buildAmount |= RPMBUILD_TRACK; /* enforce no dependency checking and expansion of %setup, %patch and %prep macros */ ba->noDeps = 1; rpmDefineMacro(NULL, "setup #", RMIL_CMDLINE); rpmDefineMacro(NULL, "patch #", RMIL_CMDLINE); rpmDefineMacro(NULL, "prep %%prep", RMIL_CMDLINE); /*@innerbreak@*/ break; case 'f': ba->buildAmount |= RPMBUILD_FETCHSOURCE; ba->noDeps = 1; /*@innerbreak@*/ break; } if (!poptPeekArg(optCon)) { if (bigMode == MODE_BUILD) argerror(_("no spec files given for build")); else argerror(_("no tar files given for build")); } while ((ba->specFile = poptGetArg(optCon))) { if (nbuilds++ > 0) { rpmFreeMacros(NULL); rpmFreeRpmrc(); (void) rpmReadConfigFiles(NULL, NULL); } ba->rootdir = rpmioRootDir; ba->passPhrase = passPhrase; ba->cookie = NULL; ec = build(ts, ba, NULL); if (ec) /*@loopbreak@*/ break; } } break; #endif /* IAM_RPMBT */ #ifdef IAM_RPMEIU case MODE_ERASE: ia->depFlags = global_depFlags; if (ia->noDeps) ia->installInterfaceFlags |= INSTALL_NODEPS; if (!poptPeekArg(optCon)) { if (ia->rbtid == 0) argerror(_("no packages given for erase")); ia->transFlags |= RPMTRANS_FLAG_NOFDIGESTS; ia->probFilter |= RPMPROB_FILTER_OLDPACKAGE; ia->rbCheck = rpmcliInstallCheck; ia->rbOrder = rpmcliInstallOrder; ia->rbRun = rpmcliInstallRun; ec += rpmRollback(ts, ia, NULL); } else { ec += rpmErase(ts, ia, (const char **) poptGetArgs(optCon)); } break; case MODE_INSTALL: /* RPMTRANS_FLAG_KEEPOBSOLETE */ ia->depFlags = global_depFlags; if (!ia->incldocs) { if (ia->transFlags & RPMTRANS_FLAG_NODOCS) { ; } else if (rpmExpandNumeric("%{_excludedocs}")) ia->transFlags |= RPMTRANS_FLAG_NODOCS; } if (ia->noDeps) ia->installInterfaceFlags |= INSTALL_NODEPS; /* we've already ensured !(!ia->prefix && !ia->relocations) */ /*@-branchstate@*/ if (ia->qva_prefix) { xx = rpmfiAddRelocation(&ia->relocations, &ia->nrelocations, NULL, ia->qva_prefix); xx = rpmfiAddRelocation(&ia->relocations, &ia->nrelocations, NULL, NULL); } else if (ia->relocations) { xx = rpmfiAddRelocation(&ia->relocations, &ia->nrelocations, NULL, NULL); } /*@=branchstate@*/ if (!poptPeekArg(optCon)) { if (ia->rbtid == 0) argerror(_("no packages given for install")); ia->transFlags |= RPMTRANS_FLAG_NOFDIGESTS; ia->probFilter |= RPMPROB_FILTER_OLDPACKAGE; ia->rbCheck = rpmcliInstallCheck; ia->rbOrder = rpmcliInstallOrder; ia->rbRun = rpmcliInstallRun; /*@i@*/ ec += rpmRollback(ts, ia, NULL); } else { /*@-compdef -compmempass@*/ /* FIX: ia->relocations[0].newPath undefined */ ec += rpmcliInstall(ts, ia, (const char **)poptGetArgs(optCon)); /*@=compdef =compmempass@*/ } break; #endif /* IAM_RPMEIU */ #ifdef IAM_RPMQV case MODE_QUERY: if (!poptPeekArg(optCon) && !(qva->qva_source == RPMQV_ALL || qva->qva_source == RPMQV_HDLIST)) argerror(_("no arguments given for query")); qva->depFlags = global_depFlags; qva->qva_specQuery = rpmspecQuery; ec = rpmcliQuery(ts, qva, (const char **) poptGetArgs(optCon)); qva->qva_specQuery = NULL; break; case MODE_VERIFY: { rpmVerifyFlags verifyFlags = VERIFY_ALL; qva->depFlags = global_depFlags; verifyFlags &= ~qva->qva_flags; qva->qva_flags = (rpmQueryFlags) verifyFlags; if (!poptPeekArg(optCon) && !(qva->qva_source == RPMQV_ALL || qva->qva_source == RPMQV_HDLIST)) argerror(_("no arguments given for verify")); ec = rpmcliVerify(ts, qva, (const char **) poptGetArgs(optCon)); } break; #endif /* IAM_RPMQV */ #ifdef IAM_RPMK case MODE_CHECKSIG: { rpmVerifyFlags verifyFlags = (VERIFY_FDIGEST|VERIFY_HDRCHK|VERIFY_DIGEST|VERIFY_SIGNATURE); verifyFlags &= ~ka->qva_flags; ka->qva_flags = (rpmQueryFlags) verifyFlags; } /*@fallthrough@*/ case MODE_RESIGN: if (!poptPeekArg(optCon)) argerror(_("no arguments given")); ka->passPhrase = passPhrase; ec = rpmcliSign(ts, ka, (const char **)poptGetArgs(optCon)); break; #endif /* IAM_RPMK */ #if !defined(IAM_RPMQV) case MODE_QUERY: case MODE_VERIFY: #endif #if !defined(IAM_RPMK) case MODE_CHECKSIG: case MODE_RESIGN: #endif #if !defined(IAM_RPMDB) case MODE_REBUILDDB: #endif #if !defined(IAM_RPMBT) case MODE_BUILD: case MODE_REBUILD: case MODE_RECOMPILE: case MODE_TARBUILD: #endif #if !defined(IAM_RPMEIU) case MODE_INSTALL: case MODE_ERASE: #endif case MODE_UNKNOWN: #ifdef DYING /* XXX rpmIsVerbose alone stops usage spewage with every --eval */ if (poptPeekArg(optCon) != NULL || argc <= 1 || rpmIsVerbose()) { printUsage(optCon, stderr, 0); ec = argc; } #endif break; } #if defined(IAM_RPMBT) || defined(IAM_RPMK) exit: #endif /* IAM_RPMBT || IAM_RPMK */ (void)rpmtsFree(ts); ts = NULL; if (pipeChild) { (void) fclose(stdout); (void) waitpid(pipeChild, &status, 0); } #ifdef IAM_RPMQV qva->qva_queryFormat = _free(qva->qva_queryFormat); #endif #ifdef IAM_RPMBT freeNames(); /* XXX _specPool/_pkgPool teardown should be done somewhere else. */ { extern rpmioPool _pkgPool; extern rpmioPool _specPool; _pkgPool = rpmioFreePool(_pkgPool); _specPool = rpmioFreePool(_specPool); } #endif #ifdef IAM_RPMEIU ia->relocations = rpmfiFreeRelocations(ia->relocations); #endif optCon = rpmcliFini(optCon); /* XXX limit the fiddle up to linux for now. */ #if !defined(HAVE_SETPROCTITLE) && defined(__linux__) (void) finiproctitle(); #endif /* XXX don't overflow single byte exit status */ /* XXX status 255 is special to xargs(1) */ if (ec > 254) ec = 254; /*@-globstate@*/ return ec; /*@=globstate@*/ }
int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QString serialPortName; QString serialPortFriendlyName; QString sisFile; QString exeFile; QStringList cmdLine; QStringList args = QCoreApplication::arguments(); QTextStream outstream(stdout); QTextStream errstream(stderr); QString uploadLocalFile; QString uploadRemoteFile; QString downloadRemoteFile; QString downloadLocalFile; int loglevel=1; int timeout=0; bool crashlog = true; QString crashlogpath; QListIterator<QString> it(args); it.next(); //skip name of program while (it.hasNext()) { QString arg = it.next(); if (arg.startsWith("-")) { if (arg == "--portname" || arg == "-p") { CHECK_PARAMETER_EXISTS serialPortName = it.next(); } else if (arg == "--portfriendlyname" || arg == "-f") { CHECK_PARAMETER_EXISTS serialPortFriendlyName = it.next(); } else if (arg == "--sis" || arg == "-s") { CHECK_PARAMETER_EXISTS sisFile = it.next(); if (!QFileInfo(sisFile).exists()) { errstream << "Sis file (" << sisFile << ") doesn't exist" << endl; return 1; } } else if (arg == "--upload" || arg == "-u") { CHECK_PARAMETER_EXISTS uploadLocalFile = it.next(); if (!QFileInfo(uploadLocalFile).exists()) { errstream << "Executable file (" << uploadLocalFile << ") doesn't exist" << endl; return 1; } CHECK_PARAMETER_EXISTS uploadRemoteFile = it.next(); } else if (arg == "--download" || arg == "-d") { CHECK_PARAMETER_EXISTS downloadRemoteFile = it.next(); CHECK_PARAMETER_EXISTS downloadLocalFile = it.next(); } else if (arg == "--timeout" || arg == "-t") { CHECK_PARAMETER_EXISTS bool ok; timeout = it.next().toInt(&ok); if (!ok) { errstream << "Timeout must be specified in milliseconds" << endl; return 1; } } else if (arg == "--verbose" || arg == "-v") loglevel=2; else if (arg == "--quiet" || arg == "-q") loglevel=0; else if (arg == "--nocrashlog") crashlog = false; else if (arg == "--crashlogpath") { CHECK_PARAMETER_EXISTS crashlogpath = it.next(); } else errstream << "unknown command line option " << arg << endl; } else { exeFile = arg; while(it.hasNext()) { cmdLine.append(it.next()); } } } if (exeFile.isEmpty() && sisFile.isEmpty() && (uploadLocalFile.isEmpty() || uploadRemoteFile.isEmpty()) && (downloadLocalFile.isEmpty() || downloadRemoteFile.isEmpty())) { printUsage(outstream, args[0]); return 1; } if (!uploadLocalFile.isEmpty() && (!downloadLocalFile.isEmpty() || !downloadRemoteFile.isEmpty())) { errstream << "Upload option can't be used together with download" << endl; printUsage(outstream, args[0]); return 1; } if (serialPortName.isEmpty()) { if (loglevel > 0) outstream << "Detecting serial ports" << endl; foreach (const SerialPortId &id, enumerateSerialPorts(loglevel)) { if (loglevel > 0) outstream << "Port Name: " << id.portName << ", " << "Friendly Name:" << id.friendlyName << endl; if (!id.friendlyName.isEmpty() && serialPortFriendlyName.isEmpty() && (id.friendlyName.contains("symbian", Qt::CaseInsensitive) || id.friendlyName.contains("s60", Qt::CaseInsensitive) || id.friendlyName.contains("nokia", Qt::CaseInsensitive))) { serialPortName = id.portName; break; } else if (!id.friendlyName.isEmpty() && !serialPortFriendlyName.isEmpty() && id.friendlyName.contains(serialPortFriendlyName)) { serialPortName = id.portName; break; } } if (serialPortName.isEmpty()) { errstream << "No phone found, ensure USB cable is connected or specify manually with -p" << endl; return 1; } } QScopedPointer<trk::Launcher> launcher; launcher.reset(new trk::Launcher(trk::Launcher::ActionPingOnly)); QFileInfo exeInfo(exeFile); QFileInfo uploadInfo(uploadLocalFile); if (!sisFile.isEmpty()) { launcher->addStartupActions(trk::Launcher::ActionCopyInstall); launcher->setCopyFileName(sisFile, "c:\\data\\testtemp.sis"); launcher->setInstallFileName("c:\\data\\testtemp.sis"); } else if (!uploadLocalFile.isEmpty() && uploadInfo.exists()) { launcher->addStartupActions(trk::Launcher::ActionCopy); launcher->setCopyFileName(uploadLocalFile, uploadRemoteFile); } if (!exeFile.isEmpty()) { launcher->addStartupActions(trk::Launcher::ActionRun); launcher->setFileName(QString("c:\\sys\\bin\\") + exeInfo.fileName()); launcher->setCommandLineArgs(cmdLine); } if (!downloadRemoteFile.isEmpty() && !downloadLocalFile.isEmpty()) { launcher->addStartupActions(trk::Launcher::ActionDownload); launcher->setDownloadFileName(downloadRemoteFile, downloadLocalFile); } if (loglevel > 0) outstream << "Connecting to target via " << serialPortName << endl; launcher->setTrkServerName(serialPortName); if (loglevel > 1) launcher->setVerbose(1); TrkSignalHandler handler; handler.setLogLevel(loglevel); handler.setCrashLogging(crashlog); handler.setCrashLogPath(crashlogpath); QObject::connect(launcher.data(), SIGNAL(copyingStarted()), &handler, SLOT(copyingStarted())); QObject::connect(launcher.data(), SIGNAL(canNotConnect(const QString &)), &handler, SLOT(canNotConnect(const QString &))); QObject::connect(launcher.data(), SIGNAL(canNotCreateFile(const QString &, const QString &)), &handler, SLOT(canNotCreateFile(const QString &, const QString &))); QObject::connect(launcher.data(), SIGNAL(canNotWriteFile(const QString &, const QString &)), &handler, SLOT(canNotWriteFile(const QString &, const QString &))); QObject::connect(launcher.data(), SIGNAL(canNotCloseFile(const QString &, const QString &)), &handler, SLOT(canNotCloseFile(const QString &, const QString &))); QObject::connect(launcher.data(), SIGNAL(installingStarted()), &handler, SLOT(installingStarted())); QObject::connect(launcher.data(), SIGNAL(canNotInstall(const QString &, const QString &)), &handler, SLOT(canNotInstall(const QString &, const QString &))); QObject::connect(launcher.data(), SIGNAL(installingFinished()), &handler, SLOT(installingFinished())); QObject::connect(launcher.data(), SIGNAL(startingApplication()), &handler, SLOT(startingApplication())); QObject::connect(launcher.data(), SIGNAL(applicationRunning(uint)), &handler, SLOT(applicationRunning(uint))); QObject::connect(launcher.data(), SIGNAL(canNotRun(const QString &)), &handler, SLOT(canNotRun(const QString &))); QObject::connect(launcher.data(), SIGNAL(applicationOutputReceived(const QString &)), &handler, SLOT(applicationOutputReceived(const QString &))); QObject::connect(launcher.data(), SIGNAL(copyProgress(int)), &handler, SLOT(copyProgress(int))); QObject::connect(launcher.data(), SIGNAL(stateChanged(int)), &handler, SLOT(stateChanged(int))); QObject::connect(launcher.data(), SIGNAL(processStopped(uint,uint,uint,QString)), &handler, SLOT(stopped(uint,uint,uint,QString))); QObject::connect(launcher.data(), SIGNAL(libraryLoaded(trk::Library)), &handler, SLOT(libraryLoaded(trk::Library))); QObject::connect(launcher.data(), SIGNAL(libraryUnloaded(trk::Library)), &handler, SLOT(libraryUnloaded(trk::Library))); QObject::connect(launcher.data(), SIGNAL(registersAndCallStackReadComplete(const QList<uint> &,const QByteArray &)), &handler, SLOT(registersAndCallStackReadComplete(const QList<uint> &,const QByteArray &))); QObject::connect(&handler, SIGNAL(resume(uint,uint)), launcher.data(), SLOT(resumeProcess(uint,uint))); QObject::connect(&handler, SIGNAL(terminate()), launcher.data(), SLOT(terminate())); QObject::connect(&handler, SIGNAL(getRegistersAndCallStack(uint,uint)), launcher.data(), SLOT(getRegistersAndCallStack(uint,uint))); QObject::connect(launcher.data(), SIGNAL(finished()), &handler, SLOT(finished())); QObject::connect(OsSignalConverter::instance(), SIGNAL(terminate()), launcher.data(), SLOT(terminate()), Qt::QueuedConnection); QTimer timer; timer.setSingleShot(true); QObject::connect(&timer, SIGNAL(timeout()), &handler, SLOT(timeout())); if (timeout > 0) { timer.start(timeout); } QString errorMessage; if (!launcher->startServer(&errorMessage)) { errstream << errorMessage << endl; return 1; } return a.exec(); }
int main( int argc, char **argv ) { int i, listenSocket[ MAX_PLAYERS ], v, longOpt; int fixedSeats, quiet; int seatFD[ MAX_PLAYERS ]; FILE *file, *logFile, *transactionFile; ReadBuf *readBuf[ MAX_PLAYERS ]; Game *game; rng_state_t rng; ErrorInfo errorInfo; struct sockaddr_in addr; socklen_t addrLen; char *seatName[ MAX_PLAYERS ]; int useLogFile, useTransactionFile; uint64_t maxResponseMicros, maxUsedHandMicros, maxUsedPerHandMicros; uint32_t numHands, seed, maxInvalidActions; uint16_t listenPort[ MAX_PLAYERS ]; char name[ MAX_LINE_LEN ]; static struct option longOptions[] = { { "t_response", 1, 0, 0 }, { "t_hand", 1, 0, 0 }, { "t_per_hand", 1, 0, 0 }, { 0, 0, 0, 0 } }; /* set defaults */ /* game error conditions */ maxInvalidActions = DEFAULT_MAX_INVALID_ACTIONS; maxResponseMicros = DEFAULT_MAX_RESPONSE_MICROS; maxUsedHandMicros = DEFAULT_MAX_USED_HAND_MICROS; maxUsedPerHandMicros = DEFAULT_MAX_USED_PER_HAND_MICROS; /* use random ports */ for( i = 0; i < MAX_PLAYERS; ++i ) { listenPort[ i ] = 0; } /* use log file, don't use transaction file */ useLogFile = 1; useTransactionFile = 0; /* print all messages */ quiet = 0; /* players rotate around the table */ fixedSeats = 0; /* parse options */ while( 1 ) { i = getopt_long( argc, argv, "flLp:qtT", longOptions, &longOpt ); if( i < 0 ) { break; } switch( i ) { case 0: /* long option longOpt */ switch( longOpt ) { case 0: /* t_response */ if( sscanf( optarg, "%"SCNu64, &maxResponseMicros ) < 1 ) { fprintf( stderr, "ERROR: could not get response timeout from %s\n", optarg ); exit( EXIT_FAILURE ); } /* convert from milliseconds to microseconds */ maxResponseMicros *= 1000; break; case 1: /* t_hand */ if( sscanf( optarg, "%"SCNu64, &maxUsedHandMicros ) < 1 ) { fprintf( stderr, "ERROR: could not get player hand timeout from %s\n", optarg ); exit( EXIT_FAILURE ); } /* convert from milliseconds to microseconds */ maxUsedHandMicros *= 1000; break; case 2: /* t_per_hand */ if( sscanf( optarg, "%"SCNu64, &maxUsedPerHandMicros ) < 1 ) { fprintf( stderr, "ERROR: could not get average player hand timeout from %s\n", optarg ); exit( EXIT_FAILURE ); } /* convert from milliseconds to microseconds */ maxUsedPerHandMicros *= 1000; break; } break; case 'f': /* fix the player seats */; fixedSeats = 1; break; case 'l': /* no transactionFile */; useLogFile = 0; break; case 'L': /* use transactionFile */; useLogFile = 1; break; case 'p': /* port specification */ if( scanPortString( optarg, listenPort ) < 0 ) { fprintf( stderr, "ERROR: bad port string %s\n", optarg ); exit( EXIT_FAILURE ); } break; case 'q': quiet = 1; break; case 't': /* no transactionFile */ useTransactionFile = 0; break; case 'T': /* use transactionFile */ useTransactionFile = 1; break; default: fprintf( stderr, "ERROR: unknown option %c\n", i ); exit( EXIT_FAILURE ); } } if( optind + 4 > argc ) { printUsage( stdout, 0 ); exit( EXIT_FAILURE ); } /* get the game definition */ file = fopen( argv[ optind + 1 ], "r" ); if( file == NULL ) { fprintf( stderr, "ERROR: could not open game definition %s\n", argv[ optind + 1 ] ); exit( EXIT_FAILURE ); } game = readGame( file ); if( game == NULL ) { fprintf( stderr, "ERROR: could not read game %s\n", argv[ optind + 1 ] ); exit( EXIT_FAILURE ); } fclose( file ); /* save the seat names */ if( optind + 4 + game->numPlayers > argc ) { printUsage( stdout, 0 ); exit( EXIT_FAILURE ); } for( i = 0; i < game->numPlayers; ++i ) { seatName[ i ] = argv[ optind + 4 + i ]; } /* get number of hands */ if( sscanf( argv[ optind + 2 ], "%"SCNu32, &numHands ) < 1 || numHands == 0 ) { fprintf( stderr, "ERROR: invalid number of hands %s\n", argv[ optind + 2 ] ); exit( EXIT_FAILURE ); } /* get random number seed */ if( sscanf( argv[ optind + 3 ], "%"SCNu32, &seed ) < 1 ) { fprintf( stderr, "ERROR: invalid random number seed %s\n", argv[ optind + 3 ] ); exit( EXIT_FAILURE ); } init_genrand( &rng, seed ); srandom( seed ); /* used for random port selection */ if( useLogFile ) { /* create/open the log */ if( snprintf( name, MAX_LINE_LEN, "%s.log", argv[ optind ] ) < 0 ) { fprintf( stderr, "ERROR: match file name too long %s\n", argv[ optind ] ); exit( EXIT_FAILURE ); } logFile = fopen( name, "a+" ); if( logFile == NULL ) { fprintf( stderr, "ERROR: could not open log file %s\n", name ); exit( EXIT_FAILURE ); } } else { /* no log file */ logFile = NULL; } if( useTransactionFile ) { /* create/open the transaction log */ if( snprintf( name, MAX_LINE_LEN, "%s.tlog", argv[ optind ] ) < 0 ) { fprintf( stderr, "ERROR: match file name too long %s\n", argv[ optind ] ); exit( EXIT_FAILURE ); } transactionFile = fopen( name, "a+" ); if( transactionFile == NULL ) { fprintf( stderr, "ERROR: could not open transaction file %s\n", name ); exit( EXIT_FAILURE ); } } else { /* no transaction file */ transactionFile = NULL; } /* set up the error info */ initErrorInfo( maxInvalidActions, maxResponseMicros, maxUsedHandMicros, maxUsedPerHandMicros * numHands, &errorInfo ); /* open sockets for players to connect to */ for( i = 0; i < game->numPlayers; ++i ) { listenSocket[ i ] = getListenSocket( &listenPort[ i ] ); if( listenSocket[ i ] < 0 ) { fprintf( stderr, "ERROR: could not create listen socket for player %d\n", i + 1 ); exit( EXIT_FAILURE ); } } /* print out the final port assignments */ for( i = 0; i < game->numPlayers; ++i ) { printf( i ? " %"PRIu16 : "%"PRIu16, listenPort[ i ] ); } printf( "\n" ); fflush( stdout ); /* print out usage information */ printInitialMessage( argv[ optind ], argv[ optind + 1 ], numHands, seed, &errorInfo, logFile ); /* wait for each player to connect */ for( i = 0; i < game->numPlayers; ++i ) { addrLen = sizeof( addr ); seatFD[ i ] = accept( listenSocket[ i ], (struct sockaddr *)&addr, &addrLen ); if( seatFD[ i ] < 0 ) { fprintf( stderr, "ERROR: seat %d could not connect\n", i + 1 ); exit( EXIT_FAILURE ); } close( listenSocket[ i ] ); v = 1; setsockopt( seatFD[ i ], IPPROTO_TCP, TCP_NODELAY, (char *)&v, sizeof(int) ); readBuf[ i ] = createReadBuf(); } /* play the match */ if( gameLoop( game, seatName, numHands, quiet, fixedSeats, &rng, &errorInfo, seatFD, readBuf, logFile, transactionFile ) < 0 ) { /* should have already printed an error message */ exit( EXIT_FAILURE ); } fflush( stderr ); fflush( stdout ); if( transactionFile != NULL ) { fclose( transactionFile ); } if( logFile != NULL ) { fclose( logFile ); } free( game ); return EXIT_SUCCESS; }
int main(int argc, char * * argv) { CipherResult cr; unsigned int cIterations; char * pszCipher; Cipher * pCipher; unsigned int cbBlock, cbKey; octet abKey[MAX_KEY_SIZE]; Key * pKey; octet abInit[MAX_BLOCK_SIZE]; octet abVector[MAX_BLOCK_SIZE]; unsigned int i; clock_t t1, t2, t3, t4; float ta, tb; char what, what2; pszProgramName = argv[0]; if (argc < 4) printUsage(1); what = argv[1][0]; if (what != 't' && what != 'v') printUsage(1); pszCipher = argv[2]; pCipher = findCipher(cipherTable, pszCipher, &cbBlock, &cbKey); assert(pCipher); if (what == 't') { if (argc != 4) printUsage(1); cIterations = atoi(argv[3]); printf("%16s-%04d-%04d: ", pCipher->pszID, cbKey * 8, cbBlock * 8); /* Dummy key. */ for (i = 0; i < cbKey; i++) abKey[i] = i; cr = cryptCreateKey(pCipher, cbBlock, cbKey, abKey, &pKey); assert(!cr); /* Initial test vector. */ for (i = 0; i < cbBlock; i++) abInit[i] = i; memcpy(abVector, abInit, cbBlock); /* Encrypt cIterations times. */ t1 = clock(); for (i = cIterations; i; i--) { pKey->pCipher->encryptBlock(pKey, abVector); } t2 = clock(); /* Decrypt cIterations times. */ t3 = clock(); for (i = cIterations; i; i--) { pKey->pCipher->decryptBlock(pKey, abVector); } t4 = clock(); /* Result should match test vector. */ for (i = 0; i < cbBlock; i++) assert(abInit[i] == abVector[i]); ta = (t2 - t1) / (float) CLOCKS_PER_SEC; tb = (t4 - t3) / (float) CLOCKS_PER_SEC; printf("%8.3f %8.3f %8.3f %8.3f\n", ta, /* time for encryption */ tb, /* time for decryption */ /* encryption speed in Mb/s */ (cbBlock * cIterations) / ta / (1024 * 1024), /* decryption speed in Mb/s */ (cbBlock * cIterations) / tb / (1024 * 1024)); } else if (what == 'v') { if (argc != 6) printUsage(1); what2 = argv[3][0]; if (what2 != 'e' && what2 != 'd') printUsage(1); readVector(argv[4], cbKey, abKey); readVector(argv[5], cbBlock, abVector); cr = cryptCreateKey(pCipher, cbBlock, cbKey, abKey, &pKey); assert(!cr); if (what2 == 'e') pKey->pCipher->encryptBlock(pKey, abVector); else pKey->pCipher->decryptBlock(pKey, abVector); for (i = 0; i < cbBlock; i++) printf("%02x", (int) abVector[i]); printf("\n"); } return 0; }
Foam::argList::argList ( int& argc, char**& argv, bool checkArgs, bool checkOpts, const bool initialise ) : args_(argc), options_(argc) { // Check if this run is a parallel run by searching for any parallel option // If found call runPar which might filter argv for (int argI = 0; argI < argc; ++argI) { if (argv[argI][0] == '-') { const char *optionName = &argv[argI][1]; if (validParOptions.found(optionName)) { parRunControl_.runPar(argc, argv); break; } } } // convert argv -> args_ and capture ( ... ) lists // for normal arguments and for options regroupArgv(argc, argv); // Get executable name args_[0] = fileName(argv[0]); executable_ = fileName(argv[0]).name(); // Check arguments and options, we already have argv[0] int nArgs = 1; argListStr_ = args_[0]; for (int argI = 1; argI < args_.size(); ++argI) { argListStr_ += ' '; argListStr_ += args_[argI]; if (args_[argI][0] == '-') { const char *optionName = &args_[argI][1]; if ( ( validOptions.found(optionName) && !validOptions[optionName].empty() ) || ( validParOptions.found(optionName) && !validParOptions[optionName].empty() ) ) { ++argI; if (argI >= args_.size()) { FatalError <<"Option '-" << optionName << "' requires an argument" << endl; printUsage(); FatalError.exit(); } argListStr_ += ' '; argListStr_ += args_[argI]; options_.insert(optionName, args_[argI]); } else { options_.insert(optionName, ""); } } else { if (nArgs != argI) { args_[nArgs] = args_[argI]; } ++nArgs; } } args_.setSize(nArgs); parse(checkArgs, checkOpts, initialise); }
int main( int argc, const char* argv[]) { strus::local_ptr<strus::ErrorBufferInterface> errorBuffer( strus::createErrorBuffer_standard( 0, 2, NULL/*debug trace interface*/)); if (!errorBuffer.get()) { std::cerr << _TXT("failed to create error buffer") << std::endl; return -1; } g_errorBuffer = errorBuffer.get(); try { bool doExit = false; int argi = 1; unsigned int transactionsize = 1000; std::pair<unsigned int,unsigned int> docnorange(0,0); std::string termtype; // Parsing arguments: for (; argi < argc; ++argi) { if (0==std::strcmp( argv[argi], "-h") || 0==std::strcmp( argv[argi], "--help")) { printUsage(); doExit = true; } else if (0==std::strcmp( argv[argi], "-v") || 0==std::strcmp( argv[argi], "--version")) { std::cerr << "strus storage version " << STRUS_STORAGE_VERSION_STRING << std::endl; doExit = true; } else if (0==std::strcmp( argv[argi], "-c") || 0==std::strcmp( argv[argi], "--commit")) { if (argi == argc || argv[argi+1][0] == '-') { throw strus::runtime_error( _TXT("no argument given to option %s"), "--commit"); } ++argi; transactionsize = parseNumber( argv[argi], "argument for option --commit"); } else if (0==std::strcmp( argv[argi], "-D") || 0==std::strcmp( argv[argi], "--docno")) { if (argi == argc || argv[argi+1][0] == '-') { throw strus::runtime_error( _TXT("no argument given to option %s"), "--docno"); } ++argi; docnorange = parseNumberRange( argv[argi], "argument for option --docno"); } else if (0==std::strcmp( argv[argi], "-T") || 0==std::strcmp( argv[argi], "--termtype")) { if (argi == argc || argv[argi+1][0] == '-') { throw strus::runtime_error( _TXT("no argument given to option %s"), "--termtype"); } ++argi; termtype = argv[ argi]; } else if (argv[argi][0] == '-') { throw strus::runtime_error(_TXT("unknown option %s"), argv[ argi]); } else { break; } } if (doExit) return 0; if (argc - argi < 3) throw strus::runtime_error( _TXT("too few arguments (given %u, required %u)"), argc - argi, 3); if (argc - argi > 3) throw strus::runtime_error( _TXT("too many arguments (given %u, required %u)"), argc - argi, 3); std::string dbconfig( argv[ argi+0]); std::string blocktype( argv[ argi+1]); unsigned int newblocksize = parseNumber( argv[argi+2], "positional argument 3"); strus::DatabaseInterface* dbi = strus::createDatabaseType_leveldb( "", g_errorBuffer); if (!dbi) throw strus::runtime_error( "%s", _TXT("could not create leveldb key/value store database handler")); if (g_errorBuffer->hasError()) throw std::runtime_error( _TXT("error in initialization")); resizeBlocks( dbi, dbconfig, blocktype, termtype, newblocksize, transactionsize, docnorange); // Check for reported error an terminate regularly: if (g_errorBuffer->hasError()) { throw strus::runtime_error( "%s", _TXT("error processing resize blocks")); } std::cerr << _TXT("done") << std::endl; return 0; } catch (const std::exception& e) { const char* errormsg = g_errorBuffer?g_errorBuffer->fetchError():0; if (errormsg) { std::cerr << e.what() << ": " << errormsg << std::endl; } else { std::cerr << e.what() << std::endl; } } std::cerr << _TXT("terminated") << std::endl; return -1; }
int main(int argc, const char* argv[]) { Arguments arguments; // // Parse the arguments // for (int i = 1; i < argc; ++i) { if (strcmp(argv[i], "-o") == 0) { i++; if (i == argc) { logError("The output folder is missing."); printUsage(); return EXIT_FAILURE; } arguments.outputFile = std::string(argv[i]); } else if (strncmp(argv[i], "-v", 2) == 0) { printVersion(); return EXIT_SUCCESS; } else if (strncmp(argv[i], "-h", 2) == 0) { printUsage(); return EXIT_SUCCESS; } else { arguments.inputPath = std::string(argv[i]); if (i != argc - 1) { logError("Archiver.exe can't archive more than one path!"); return EXIT_FAILURE; } } } if (arguments.inputPath == "" || arguments.outputFile == "") { logError("Invalid arguments!", arguments.inputPath.c_str()); printUsage(); return EXIT_FAILURE; } // // Check if the input path exists // DWORD dwAttrib = GetFileAttributesA(arguments.inputPath.c_str()); bool exists = ((dwAttrib != INVALID_FILE_ATTRIBUTES) && (dwAttrib & FILE_ATTRIBUTE_DIRECTORY)); if (!exists) { logError("The %s doesn't exists or is not a directory."); return EXIT_FAILURE; } // // Archive the folder // Archiver archiver(arguments); if (!archiver.archive()) { return EXIT_FAILURE; } // If debugger is present, a pause is required to keep the console output // visible. Otherwise the pause is automatic. if (IsDebuggerPresent()) { system("pause"); } return EXIT_SUCCESS; }