Example #1
0
int
main(int argc, char *argv[])
{
    netsnmp_session session, *ss;
    netsnmp_pdu    *pdu, *response;
    netsnmp_variable_list *vars;
    int             arg;
    char           *gateway;

    int             count;
    struct varInfo *vip;
    u_int           value = 0;
    struct counter64 c64value;
    float           printvalue;
    time_t          last_time = 0;
    time_t          this_time;
    time_t          delta_time;
    int             sum;        /* what the heck is this for, its never used? */
    char            filename[128] = { 0 };
    struct timeval  tv;
    struct tm       tm;
    char            timestring[64] = { 0 }, valueStr[64] = {
    0}, maxStr[64] = {
    0};
    char            outstr[256] = { 0 }, peakStr[64] = {
    0};
    int             status;
    int             begin, end, last_end;
    int             print = 1;
    int             exit_code = 0;

    switch (arg = snmp_parse_args(argc, argv, &session, "C:", &optProc)) {
    case -2:
        exit(0);
    case -1:
        usage();
        exit(1);
    default:
        break;
    }

    gateway = session.peername;

    for (; optind < argc; optind++) {
	if (current_name >= MAX_ARGS) {
	    fprintf(stderr, "%s: Too many variables specified (max %d)\n",
	    	argv[optind], MAX_ARGS);
	    exit(1);
	}
        varinfo[current_name++].name = argv[optind];
    }

    if (current_name == 0) {
        usage();
        exit(1);
    }

    if (dosum) {
	if (current_name >= MAX_ARGS) {
	    fprintf(stderr, "Too many variables specified (max %d)\n",
	    	MAX_ARGS);
	    exit(1);
	}
        varinfo[current_name++].name = 0;
    }

    SOCK_STARTUP;

    /*
     * open an SNMP session 
     */
    ss = snmp_open(&session);
    if (ss == NULL) {
        /*
         * diagnose snmp_open errors with the input netsnmp_session pointer 
         */
        snmp_sess_perror("snmpdelta", &session);
        SOCK_CLEANUP;
        exit(1);
    }

    if (tableForm && timestamp) {
        printf("%s", gateway);
    }
    for (count = 0; count < current_name; count++) {
        vip = varinfo + count;
        if (vip->name) {
            vip->oidlen = MAX_OID_LEN;
            vip->info_oid = (oid *) malloc(sizeof(oid) * vip->oidlen);
            if (snmp_parse_oid(vip->name, vip->info_oid, &vip->oidlen) ==
                NULL) {
                snmp_perror(vip->name);
                SOCK_CLEANUP;
                exit(1);
            }
            sprint_descriptor(vip->descriptor, vip);
            if (tableForm)
                printf("\t%s", vip->descriptor);
        } else {
            vip->oidlen = 0;
            strcpy(vip->descriptor, SumFile);
        }
        vip->value = 0;
        zeroU64(&vip->c64value);
        vip->time = 0;
        vip->max = 0;
        if (peaks) {
            vip->peak_count = -1;
            vip->peak = 0;
            vip->peak_average = 0;
        }
    }

    wait_for_period(period);

    end = current_name;
    sum = 0;
    while (1) {
        pdu = snmp_pdu_create(SNMP_MSG_GET);

        if (deltat)
            snmp_add_null_var(pdu, sysUpTimeOid, sysUpTimeLen);

        if (end == current_name)
            count = 0;
        else
            count = end;
        begin = count;
        for (; count < current_name
             && count < begin + varbindsPerPacket - deltat; count++) {
            if (varinfo[count].oidlen)
                snmp_add_null_var(pdu, varinfo[count].info_oid,
                                  varinfo[count].oidlen);
        }
        last_end = end;
        end = count;

      retry:
        status = snmp_synch_response(ss, pdu, &response);
        if (status == STAT_SUCCESS) {
            if (response->errstat == SNMP_ERR_NOERROR) {
                if (timestamp) {
                    gettimeofday(&tv, (struct timezone *) 0);
                    memcpy(&tm, localtime((time_t *) & tv.tv_sec),
                           sizeof(tm));
                    if (((period % 60)
                         && (!peaks || ((period * peaks) % 60)))
                        || keepSeconds)
                        sprintf(timestring, " [%02d:%02d:%02d %d/%d]",
                                tm.tm_hour, tm.tm_min, tm.tm_sec,
                                tm.tm_mon + 1, tm.tm_mday);
                    else
                        sprintf(timestring, " [%02d:%02d %d/%d]",
                                tm.tm_hour, tm.tm_min,
                                tm.tm_mon + 1, tm.tm_mday);
                }

                vars = response->variables;
                if (deltat) {
                    if (!vars || !vars->val.integer) {
                        fprintf(stderr, "Missing variable in reply\n");
                        continue;
                    } else {
                        this_time = *(vars->val.integer);
                    }
                    vars = vars->next_variable;
                } else {
                    this_time = 1;
                }

                for (count = begin; count < end; count++) {
                    vip = varinfo + count;

                    if (vip->oidlen) {
                        if (!vars || !vars->val.integer) {
                            fprintf(stderr, "Missing variable in reply\n");
                            break;
                        }
                        vip->type = vars->type;
                        if (vars->type == ASN_COUNTER64) {
                            u64Subtract(vars->val.counter64,
                                        &vip->c64value, &c64value);
                            memcpy(&vip->c64value, vars->val.counter64,
                                   sizeof(struct counter64));
                        } else {
                            value = *(vars->val.integer) - vip->value;
                            vip->value = *(vars->val.integer);
                        }
                        vars = vars->next_variable;
                    } else {
                        value = sum;
                        sum = 0;
                    }
                    delta_time = this_time - vip->time;
                    if (delta_time <= 0)
                        delta_time = 100;
                    last_time = vip->time;
                    vip->time = this_time;
                    if (last_time == 0)
                        continue;

                    if (vip->oidlen && vip->type != ASN_COUNTER64) {
                        sum += value;
                    }

                    if (tableForm) {
                        if (count == begin) {
                            sprintf(outstr, "%s", timestring + 1);
                        } else {
                            outstr[0] = '\0';
                        }
                    } else {
                        sprintf(outstr, "%s %s", timestring,
                                vip->descriptor);
                    }

                    if (deltat || tableForm) {
                        if (vip->type == ASN_COUNTER64) {
                            fprintf(stderr,
                                    "time delta and table form not supported for counter64s\n");
                            exit(1);
                        } else {
                            printvalue =
                                ((float) value * 100) / delta_time;
                            if (tableForm)
                                sprintf(valueStr, "\t%.2f", printvalue);
                            else
                                sprintf(valueStr, " /sec: %.2f",
                                        printvalue);
                        }
                    } else {
                        printvalue = (float) value;
                        sprintf(valueStr, " /%d sec: ", period);
                        if (vip->type == ASN_COUNTER64)
                            printU64(valueStr + strlen(valueStr),
                                     &c64value);
                        else
                            sprintf(valueStr + strlen(valueStr), "%u",
                                    value);
                    }

                    if (!peaks) {
                        strcat(outstr, valueStr);
                    } else {
                        print = 0;
                        if (vip->peak_count == -1) {
                            if (wait_for_peak_start(period, peaks) == 0)
                                vip->peak_count = 0;
                        } else {
                            vip->peak_average += printvalue;
                            if (vip->peak < printvalue)
                                vip->peak = printvalue;
                            if (++vip->peak_count == peaks) {
                                if (deltat)
                                    sprintf(peakStr,
                                            " /sec: %.2f	(%d sec Peak: %.2f)",
                                            vip->peak_average /
                                            vip->peak_count, period,
                                            vip->peak);
                                else
                                    sprintf(peakStr,
                                            " /%d sec: %.0f	(%d sec Peak: %.0f)",
                                            period,
                                            vip->peak_average /
                                            vip->peak_count, period,
                                            vip->peak);
                                vip->peak_average = 0;
                                vip->peak = 0;
                                vip->peak_count = 0;
                                print = 1;
                                strcat(outstr, peakStr);
                            }
                        }
                    }

                    if (printmax) {
                        if (printvalue > vip->max) {
                            vip->max = printvalue;
                        }
                        if (deltat)
                            sprintf(maxStr, "	(Max: %.2f)", vip->max);
                        else
                            sprintf(maxStr, "	(Max: %.0f)", vip->max);
                        strcat(outstr, maxStr);
                    }

                    if (print) {
                        if (fileout) {
                            sprintf(filename, "%s-%s", gateway,
                                    vip->descriptor);
                            print_log(filename, outstr + 1);
                        } else {
                            if (tableForm)
                                printf("%s", outstr);
                            else
                                printf("%s\n", outstr + 1);
                            fflush(stdout);
                        }
                    }
                }
                if (end == last_end && tableForm)
                    printf("\n");
            } else {
                if (response->errstat == SNMP_ERR_TOOBIG) {
                    if (response->errindex <= varbindsPerPacket
                        && response->errindex > 0) {
                        varbindsPerPacket = response->errindex - 1;
                    } else {
                        if (varbindsPerPacket > 30)
                            varbindsPerPacket -= 5;
                        else
                            varbindsPerPacket--;
                    }
                    if (varbindsPerPacket <= 0) {
                        exit_code = 5;
                        break;
                    }
                    end = last_end;
                    continue;
                } else if (response->errindex != 0) {
                    fprintf(stderr, "Failed object: ");
                    for (count = 1, vars = response->variables;
                         vars && count != response->errindex;
                         vars = vars->next_variable, count++);
                    if (vars)
                        fprint_objid(stderr, vars->name,
                                     vars->name_length);
                    fprintf(stderr, "\n");
                    /*
                     * Don't exit when OIDs from file are not found on agent
                     * exit_code = 1;
                     * break;
                     */
                } else {
                    fprintf(stderr, "Error in packet: %s\n",
                            snmp_errstring(response->errstat));
                    exit_code = 1;
                    break;
                }

                /*
                 * retry if the errored variable was successfully removed 
                 */
                if (!netsnmp_ds_get_boolean(NETSNMP_DS_APPLICATION_ID, 
					    NETSNMP_DS_APP_DONT_FIX_PDUS)) {
                    pdu = snmp_fix_pdu(response, SNMP_MSG_GET);
                    snmp_free_pdu(response);
                    response = NULL;
                    if (pdu != NULL)
                        goto retry;
                }
            }

        } else if (status == STAT_TIMEOUT) {
            fprintf(stderr, "Timeout: No Response from %s\n", gateway);
            response = 0;
            exit_code = 1;
            break;
        } else {                /* status == STAT_ERROR */
            snmp_sess_perror("snmpdelta", ss);
            response = 0;
            exit_code = 1;
            break;
        }

        if (response)
            snmp_free_pdu(response);
        if (end == current_name) {
            wait_for_period(period);
        }
    }
    snmp_close(ss);
    SOCK_CLEANUP;
    return (exit_code);
}
int main( int argc, char **argv )
{

/******************************************************************************************

  Random number guessing game in a couple of lines. "Not pretty, but fairly short" version.

*******************************************************************************************/

#ifdef NBR_GAME
#define P printf
 int r, a=4, i=0, A=1, Z=10; srand(time(0));

 for( P("%d..%d\n",A,Z),r=(rand()%(Z-A+1))+A; r^i&&(a--?P("(try %d/4)?:",4-a): !P("Comp wins! (was:%d)",r)); )
 {
    scanf("%d",&i); P("%s\n",r>i?"Mine's >":r<i?"Mine's <":"Got it.\nYou win!");
 }
#endif




/******************************************************************************************

    A version of Mastermind, but based on numbers, not colors
    (http://en.wikipedia.org/wiki/Mastermind_(game))

*******************************************************************************************/

#ifdef MM_GAME

#define DIGITS 3

 char inp[10] = {0}, nr[DIGITS+1] = {0};
 int i, guess = 0, rplace = 0, wplace = 0;

 srand(time(NULL));

 for( i = 0; i < DIGITS; i++ ) nr[i] = '0' + rand() % 10;


 while( rplace != DIGITS )
 {
     printf("\n Enter number (%d digits): ", DIGITS);
     scanf("%s3", &inp);

     rplace = wplace = 0;
     guess++;

     for( i = 0; i < DIGITS; i++ )
     {
        if (inp[i] == nr[i]) rplace++; else if (strchr(nr,inp[i])) wplace++;
     }

      printf("\n Right place: %d, Wrong place: %d, attempts: %d", rplace, wplace, guess );
 }

 puts("\n Got it!");


#endif



/******************************************************************************************

  Minimal passwort / token generator, based on a formated input string.
  Example: 5000x0xxx

           first digit (in HEX): generate 5 results
           each '0': replace with random number
           each 'x': replace with random character

*******************************************************************************************/

#ifdef PWDGEN
#define MAXLEN 20
 int i, r;
 char inp[MAXLEN] = {0}, outp[MAXLEN] = {0};

 printf("\nInput:");
 scanf("%s20", &inp);

 if ( *inp >='a' && *inp <='f' ) r = *inp-'a'+10; else
 if ( *inp >='0' && *inp <='9' ) r = *inp-'0';

 srand( time(NULL) );

 while(r--)
 {
     for(i = 1; i < strlen(inp); i++)
         outp[i-1] = (inp[i]=='0') ? outp[i-1]='0' + rand() % 10:
                     (inp[i]=='x') ? outp[i-1]='a' + rand() % 26: inp[i];

     printf("\n (%2.d) pwd: %s", r + 1, outp);
 }
#endif

/******************************************************************************************

  Minimal ANSI art viewer. Work in progress.

*******************************************************************************************/

#ifdef ANSIART

#define ESC 0x1B
#define LEFTBRACKET '['

 char * filename = "ab-onion.ans";
 char * out[100][80];
 char inp, c, a, b;
 int i, count = 0;
 int x, y, sx, sy;

 for( y = 0; y < 100;  y++ )
 for( x = 0; x <  80;  x++ )
 {
     out[y][x] = 0x20;
 }

 FILE *f = fopen(filename, "r");

 if(f == NULL)
 {
    printf("\nError opening file <%s>\n", filename);
    return -1;
 }
 else
 {
     printf("\nReading file <%s>", filename);

     /* cache file first */
     char in[200*80] = {'\0'};

     i = 0;
     while( (in[i++] = fgetc(f)) != EOF && i < 100*80 );

     fclose(f);

     printf("\nDone reading file (%d bytes).\n", i);
     system("PAUSE");

     x = y = sx = sy = 0;
     i = -1;

     while( in[++i] )
     {

        if (in[i] != ESC)
        {
            //printf("\nline: %d, x: %d -> %c", y,x,in[i]);
            out[y][x] = in[i];
            if (in[i] == '\n') y++;
            x++;
        }
        else
        if ( in[i] == ESC && in[i+1] == LEFTBRACKET )
        {
            /* interpret sequence */
            /* crs up        -> CSI n A */
            /* crs down      -> CSI n B */
            /* crs forw      -> CSI n C */
            /* crs back      -> CSI n D */
            /* crs next line -> CSI n E */
            /* crs prev line -> CSI n F */
            /* crs horz absol-> CSI n G */

            /* save    position -> CSI s */
            /* restore position -> CSI r */

            char cmds[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 's', 'r' };

            /* TODO: look for trailing command first */

            i += 2;
            char param   = in[i];
            char command = in[i+1];

            if(param == 's') { sx =  x;  sy =  y; }
            if(param == 'r') { x  = sx;  y  = sy; }

            switch(command)
            {
                case 'A': y -= param; break;
                case 'B': y += param; break;
                case 'C': x += param; break;
                case 'D': x -= param; break;
                case 'E': x  = 0; y += param; break;
                case 'F': x  = 0; y -= param; break;
                case 'G': x  = param; break;
                case ';': a = in[i+2];
                          b = in[i+3];
                          if (b =='f' || b == 'H') { x = a; y = param; }
                          break;
            }

        }
        else
        {
            /* ... */
        }

     }

    printf("\n Buffer contents: \n");

     for( y = 0; y <  80;  y++ )
     for( x = 0; x < 100;  x++ )
     {
         printf( "%c", out[y][x] );
     }

 }


#endif


/******************************************************************************************

  Tiny memory editor / viewer / file dumper utility.
  Enough features to have its own little help screen. :)

*******************************************************************************************/

#ifdef MEDT

 #define KEY_ADR   'i'
 #define KEY_ASCII 'a'
 #define KEY_HEX   'h'
 #define KEY_DUMP  'd'
 #define KEY_FILL  'f'
 #define KEY_REPL  'r'
 #define KEY_HELP  '?'
 #define KEY_QUIT  'q'

 #define CHAR_DUMMY '.'

 char *adr;
 char inp[40] = {0};
 char *mstart = (char*)inp;
 char *mend   = mstart + 0xFF;

 int cont = 1;

 printf("\nMEDT - 1.0a; %c = help", KEY_HELP);

 while (cont)
 {
    printf("\n\n[adr: %X-%X]>:", mstart, mend);

    scanf("%s40", inp);

    if (*inp == KEY_HELP)
    {
        printf("\n %c - This help screen", KEY_HELP);
        printf("\n %c - Input memory adress range", KEY_ADR);
        printf("\n %c - Display range as ASCII chars", KEY_ASCII);
        printf("\n %c - Display range as HEX values", KEY_HEX);
        printf("\n %c - Save range as a file", KEY_DUMP);
        printf("\n %c - Fill range with byte", KEY_FILL);
        printf("\n %c - Search and replace byte in range with byte", KEY_REPL);
        printf("\n %c - Quit\n", KEY_QUIT);
    }
    else if (*inp == KEY_ADR)
    {
        int adr1, adr2;

        printf("\nAdresses (HEX) [start, end]:");
        scanf("%X, %X", &adr1, &adr2);

        mstart = (char*)adr1;
        mend   = (char*)adr2;
    }
    else if (*inp == KEY_FILL)
    {
        int val;

        printf("\nFill with byte (HEX) [value]: ");
        scanf("%X", val);

        for( adr = mstart; adr < mend; adr++ ) *adr = val & 0xFF;
    }
    else if (*inp == KEY_REPL)
    {
        int val1, val2;
        int count = 0;

        printf("\nSearch and replace byte x with value y (HEX) [x, y]: ");
        scanf("%X,%X", &val1, &val2 );

        for( adr = mstart; adr < mend; adr++ )
        {
            if (*adr == (val1 & 0xFF)) { *adr = val2 & 0xFF; count++; }
        }

        printf("\n%d bytes found and replaced.\n", count);
    }
    else if (*inp == KEY_ASCII)
    {
        printf("\nMemory at (ASCII display mode): %X - %X\n\n", mstart, mend);

        /* printable 7Bit ASCII chars only, DUMMY_CHAR for the rest, 60 chars each line */
        for( adr = mstart; adr < mend; adr++ )
        {
            printf("%c%s", (*adr >= 0x20 && *adr <= 0x7E) ? *adr : CHAR_DUMMY, !((adr - mstart + 1) % 60) ? "\n" : "" );
        }
    }
    else if (*inp == KEY_HEX)
    {
        printf("\nMemory at (HEX display mode): %X - %X\n\n", mstart, mend);

        /* separated hex values, 20 per line. leading 0, if needed */
        for( adr = mstart; adr < mend; adr++ )
        {
            char val = *adr & 0x0F;
            printf("-%s%X%s", (val < 0x10) ? "0" : "", val, !((adr - mstart + 1) % 20) ? "\n" : "" );
        }
    }
    else if (*inp == KEY_DUMP)
    {
        char filename[80] = "";

        printf("\nPath/filename: ");
        scanf("%s80", filename);

        printf("\nWriting file to disk... ");

        FILE *f = fopen(filename,"wb");

        if (f != NULL)
        {
            for( adr = mstart; adr < mend; adr++ ) fputc(*adr & 0xFF, f);
            fclose(f);
            printf("done.\n");
        }
        else printf("Error!\n");
    }

    if ( !strcmp(inp,"exit") || *inp == KEY_QUIT ) cont = 0;
 }

#endif



/******************************************************************************************

    A version of Picross.

    A Logic / Picture Puzzle Game. Unfinished.
    (http://en.wikipedia.org/wiki/Picross)

*******************************************************************************************/

#ifdef PICROSS_GAME

 #define F_SIZE      10
 #define PIC_COUNT    2
 #define BASE_CHAR 0x22
 #define CODE_CHAR   97

 int i,i2, x,y, cx,cy,cn;

 char f[F_SIZE*F_SIZE] = {0};
 char n[F_SIZE]        = {0};

 char nh[F_SIZE][F_SIZE]; /* hor: line, row */
 char nv[F_SIZE][F_SIZE]; /* ver: line, row */

 memset( nh, 0, sizeof(nh) );
 memset( nv, 0, sizeof(nv) );


 char pics[PIC_COUNT][F_SIZE*F_SIZE];

 strcpy( pics[0], "-------------oooo-----o-o--o---o---o--o-o-----oooo-o---o--o---o-o--o-----oooo-----------------------" );
 strcpy( pics[1], "-------------ooo------o--o-----o---oooooo--------oo--------o-o---ooooo--o--o-------ooo--------------" );
 strcpy( pics[2], "" );
/* => 110, 101, 102, 98, 98, 98, 99, ..

 - 97 + 13
 o 97 +  4
 - 97 +  5
 o 97 +  1
 - 97 +  1
 o 97 +  1
 - 97 +  2
 ...
*/

/* lv1                      lv2                     lv3
  - - - - - - - - - -       - - - - - - - - - -     o o o o o o o o - o
  - - - o o o o - - -       - - - o o o - - - -     - - - o - - - o - o
  - - o - o - - o - -       - - o - - o - - - -     o - o o - o o o - -
  - o - - - o - - o -       - o - - - o o o o o     o - - - - - - o - o
  o - - - - - o o o o       o - - - - - - - - o     o o o - - - - o - o
  - o - - - o - - o -       o - - - - - - - - o     - o - - o o o o - o
  - - o - o - - o - -       - o - - - o o o o o     - o - - - - o - - -
  - - - o o o o - - -       - - o - - o - - - -     o o o o o - o o - o
  - - - - - - - - - -       - - - o o o - - - -     o - - - - - - - - o
  - - - - - - - - - -       - - - - - - - - - -     o o o o o o o o o o
*/

/*----------------------------------------------------------------------------------*/

 /* select random pic, or a randomly generated pic */
 if ( rand()%(PIC_COUNT+1) < PIC_COUNT )
 {
    int cell = 0;
    char set = 0;

     /* decode pic data, if needed */
     /*
     for(i  = 0; i < strlen(pics[lv]); i++ )
     {
        int inrow = pics[lv][i] - CODE_CHAR;
        for(i2 = 0; i2 < inrow; i2++ ) f[cell++] = set;
        set = !set;
     }
     */

     /* no decoding */
    for(i = 0; i < sizeof(f); i++)
        f[i] = (pic[lv][i] == 'o') ? 1 : 0;
 }
 else
 {
    srand( time(NULL) );

    for(i = 0; i < sizeof(f); i++)
        f[i] = rand() % 5 ? 0 : 1;
 }


 /*----------------------------------------------------------------------------------*/


 int inpx = 0, inpy = 0, cont = 1, turns = 0;

 /* main input loop; */
 while( cont )
 {

    /* scan field -> horizontal [TODO: vertical; outter: x, inner: y] */
    for(y = 0, cy = 0; y < F_SIZE; y++)
    {
        /* start with no row results */
        memset(n, 0, F_SIZE);

        for( x = 0, cx = 0, cn = 0; x < F_SIZE; x++ )
        {
            /* count stones in a row */
            if ( f[x + F_SIZE*y] ) cx++;
            /* gap or corner stone? -> add results to n[] */
            if (cx && (!f[x+F_SIZE*y] || x == F_SIZE-1) ) { n[cn++] = cx + '0'; cx = 0; }
        }
        /* nh = string together all horizontal results, line breaks after each line */
        strcat(n, strlen(n) ? "": "none");
        strcat(nh[y], n);
    }

    /* show field + right hints per line */
    for( i = 1; i <= sizeof(f); i++ )
    {
        printf( "%c", f[i-1] + BASE_CHAR );
        if ( !(i % F_SIZE) ) printf(" %s\n", nh[(i-1)/F_SIZE] );
    }

    /* bottom hints; test with HOR. hint numbers; TODO for vert. numbers */
    for( i = 0; i < F_SIZE; i++ )
    {
        int validln = 0;
        char row[F_SIZE+1] = {0};

        for(i2 = 0; i2 < F_SIZE; i2++)
            if ((row[i2] = nh[i2][i] ? nh[i2][i] : ' ') != ' ') validln = 1;

        if (validln) printf("%s\n", row);
    }

    /*----------------------------------------------------------------------------------*/

    printf("\nTurn: %d, Enter x,y (0..9, 0..9, diff. coords to quit):", ++turns);
    scanf("%i,%i", &inpx, &inpy);

    /* check for exit */
    cont = ( (inpx*inpy) >= 0) && ((inpx*inpy) < sizeof(f) );

    if (cont)
    {
      printf("%d, %d -> %s", inpx, inpy, f[F_SIZE * inpy + inpx] ? "Hit!" : "Miss!" );
      f[F_SIZE*inpy + inpx] = 0;

      /* no stones left to uncover? level complete */
      char fclear = 1;
      for( i = 0; i < F_SIZE && (fclear = !f[i]); i++ )

      if(fclear)
      {
          printf("\Pic uncovered (in %d turns)! Congratulation", turns);
          cont = 0;
      }

    }

 }

 system("PAUSE");

#endif



/******************************************************************************************

    Estimation Game
    Guess what number is the most common in a random number field.

*******************************************************************************************/

#ifdef EST_GAME

#define F_SIZE 14
#define DIFFICULTY 5

 int  i, a, nr, higher = 0, ce[DIFFICULTY] = {0};
 char f[ F_SIZE * F_SIZE ] = {0};
 time_t t = time(NULL);

 srand(t); puts("");

 for(i = 0; i < F_SIZE * F_SIZE; i++)
 {
     printf(" %d%s", nr = rand() % DIFFICULTY, ! ((i+1)%F_SIZE) ? "\n" : "" );
     ce[nr]++;
 }

 printf("\n Most common? :");
 scanf("%10d", &a);

 for(i = 0; i < DIFFICULTY; i++)
   if (a != i && ce[i] > ce[a]) higher++;

 if ( !higher ) printf(" Correct! (in: %d seconds)", time(NULL)-t); else
                printf(" Wrong! (%d other number(s) are more common)", higher);

 printf("\n Counts: ");
 for(i = 0; i < DIFFICULTY; i++)
     printf("%d = %d%s ", i, ce[i], (i != DIFFICULTY-1) ? "," : "." );

 puts("\n");
 system("PAUSE");

#endif



/******************************************************************************************

    (Text-)file appending / copy / filter tool

    - can add EOF text markers
    - filter out extended ASCII
    - convert Umlauts and Esszett
    - apply 1990s style l33t sp34k ;)

*******************************************************************************************/

#ifdef FMERGE

#define MAX_FILE_COUNT 99

/* TODO: currently only works with markers + one add. flag */

  char HELP_TEXT[] =
    "\nUsage: fmerge [parameters]\n"
    "\nFirst parameter not recognized as an option  = output filename."
    "\nAll other unrecognized parameters following  = input filename(s)."
    "\n\nOptions:"
    "\n --m  : Insert EOF markers."
    "\n --d  : Convert Umlaut and Esszett characters."
    "\n --7  : 7 Bit ASCII only. Extented ASCII chars will be replaced with a dash."
    "\n --l  : L33t Sp43k filter.\n"
    "\nNote that --d, --7 and --l cannot be mixed.";

 char infilenames[ MAX_FILE_COUNT ][250];
 char outfilename[250];

 FILE *infile, *outfile;

 char norm_chars[] = "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
 char leet_chars[] = "4bcd3fgh1jklmn0pqr5+uvwxyz" "48CD3FGH1JK7MNOPQR$+UVWXYZ";

 char de_chars[] = "הצ�ִײ��";

 char flag_markers = 0,
      flag_deconv  = 0,
      flag_7bit    = 0,
      flag_leet    = 0;

 char fcount = 0, c;
 int i, pos;

 /* cmd line checking ..
    - first unrecognized option/parameter      = output filename
    - all other unrecognized parameters after  = input filenames
 */
 if (argc > 2)
 {
     for( i = 1; i < argc; i++ )
     {
         if      (!strcmp(argv[i], "--m")) flag_markers = 1;
         else if (!strcmp(argv[i], "--d")) flag_deconv  = 1;
         else if (!strcmp(argv[i], "--7")) flag_7bit    = 1;
         else if (!strcmp(argv[i], "--l")) flag_leet    = 1;
         else
         {
            if (fcount > 0)
                strncpy( infilenames[fcount-1], argv[i], 250 );
            else
                strncpy( outfilename, argv[i], 250 );

            fcount++;
         }
     }
 }

 if (fcount < 2)
 {
     puts("Error: At least one input and one output file required.");
     puts(HELP_TEXT);
     return -1;
 }

 if ( (flag_deconv + flag_7bit + flag_leet) > 1)
 {
    puts("Error: Too many parameters."
         "Only one of the following parameters permitted per run: --f, --7, --l");

    puts(HELP_TEXT);
    return -1;
 }

 outfile = fopen( outfilename, "wb" );

 printf("\Appending %d file(s) and save as <%s>\n", fcount-1, outfilename);
 printf( "\nFlags Overview:"
         "\n - 7bit only    : %s"
         "\n - DE-Char Conv : %s"
         "\n - L33T sp34k   : %s"
         "\n - EOF-Markers  : %s\n",
         flag_7bit    ? "yes" : "no",
         flag_deconv  ? "yes" : "no",
         flag_leet    ? "yes" : "no",
         flag_markers ? "yes" : "no" );


 for( i = 0; i < fcount-1; i++ )
 {
    infile = fopen(infilenames[i], "rb");

    if (infile)
    {
        if (flag_leet)
        {
            while ( (c = fgetc(infile)) != EOF)
            {
              if ( (pos = (strchr(norm_chars, c) - norm_chars)) >= 0 )
                fputc( leet_chars[pos], outfile);
              else
                fputc(c, outfile);
            }
        }
        else if (flag_7bit)
        {
            while ( (c = fgetc(infile)) != EOF)
               if (c >= 0) fputc(c, outfile); else fputc('-', outfile);
        }
        else if (flag_deconv)
        {
            char oldc;

            while ( (c   = fgetc(infile)) != EOF )
               if ( (pos = (strchr(de_chars, c) - de_chars)) >= 0  )
               {
                    if (pos == 0) fputs("ae", outfile);
                    if (pos == 1) fputs("oe", outfile);
                    if (pos == 2) fputs("ue", outfile);
                    if (pos == 3) fputs("AE", outfile);
                    if (pos == 4) fputs("OE", outfile);
                    if (pos == 5) fputs("UE", outfile);

                    /* since there's no capital Esszett, we need some context for conversion */
                    if (pos == 6) { fputs( (oldc >= 0x61) ? "ss" : "SS", outfile); }
               }
               else fputc(oldc = c, outfile);
        }

        if (flag_markers)
        {
            char marker[200] = "\r\n---- end of file < ";

            strncat( marker, infilenames[i], 160 );
            strcat(  marker, " > ----\r\n" );

            fputs( marker, outfile );
        }

        printf( "\n<%s> Ok.", infilenames[i] );
    }
    else
        printf( "\n<%s> Error opening file", infilenames[i] );

    fclose( infile );

 }

 fclose( outfile );
 puts("");


#endif


/******************************************************************************************

    Fisher-Yates / Durstenfeld-Shuffle with presets
    (useful for searching for anagrams or just trying to come up with project names ;)

*******************************************************************************************/

#ifdef PERM
#define LOOPS 20

 int i, j, r;
 char inp[40], tmp;

 srand(time(NULL));

 printf("String to shuffle, [shortcuts: a-z, 0-9, dice]: ");
 scanf("%s40", &inp);

 if ( !strcmp(inp, "a-z" ) ) strcpy(inp, "abcdefghijklmnopqrstuvwxyz");
 if ( !strcmp(inp, "0-9" ) ) strcpy(inp, "0123456789");
 if ( !strcmp(inp, "dice") ) strcpy(inp, "123456");

 for( j = LOOPS; j-- > 0; )
 {
     for( i = strlen(inp); i-- > 1; )
     {
        r = rand() % i;

        tmp    = inp[i];
        inp[i] = inp[r];
        inp[r] = tmp;
     }

     printf("<%s>\n", inp);
 }

 system("PAUSE");

#endif

/******************************************************************************************

 SBFED = Super Bad File Encoding & Decoding

 (shortest and possibly worst mini file encrypter/decrypter possible. Don't use this
  for your billion dollar trade secrets. ;)

*******************************************************************************************/
#ifdef SBFED

 if (argc != 3) { puts("Error: 2 params for in/out files needed."); return -1; };

 FILE *sf = fopen( argv[1], "rb");
 FILE *df = fopen( argv[2], "wb");

 char c;
 while( (c = fgetc(sf)) != EOF ) fputc( (((c^-1) & 0xF0) >> 4) | (((c^-1) & 0x0F) << 4), df );

 fclose(sf);
 fclose(df);

#endif

/******************************************************************************************

    Prime Number Evaluation. Short, simple & fast enough. AKS this is not, though.

*******************************************************************************************/
#ifdef PRIME

 /* Beware: C99 stuff. ANSI/C89-only compilant compilers might argue this. */
 long long int i, p, isprime = 1;

 printf("\nNumber:");
 scanf("%lld", &p);

 if (p == 2) isprime = 1;
 else
 if (p < 2 || !(p % 2)) isprime = 0;
 else
 for(i = 3; ( i <= sqrt(p)) && (isprime = p % i); i += 2);

 printf("\nPrime: %s\n", isprime ? "Yes" : "No");

#endif


/******************************************************************************************

    (ANTI-)JOKE GENERATOR. NOTHING IS SACRED!
    "Why did the charming bulldozer run over the research facility?"
    "Because the bulldozer could not love a(n) upset aroma therapist!"

*******************************************************************************************/
#ifdef AJOKE

 srand(time(NULL));

 char *a[] = { "chicken", "astronaut", "bulldozer", "aroma therapist", "pole dancer" };
 char *b[] = { "cross", "run over", "walk over", "talk to", "love" };
 char *c[] = { "street", "bridge", "chicken farm", "rumba instructor meeting hall", "research facility" };
 char *d[] = { "bossy", "charming", "single", "blushing", "upset" };

 printf("\nWhy did the %s %s %s the %s?", d[rand()%5], a[rand()%5], b[rand()%5], c[rand()%5] );
 printf("\nBecause the %s could not %s a(n) %s %s!\n", a[rand()%5], b[rand()%5], d[rand()%5], a[rand()%5] );

#endif

 return 0;

}
Example #3
0
void TreatVariations(char *fileName)
{
	char line[LineSize];	// pointer to the line read from the netlist file
	FILE *inputFd;			// file descriptor, used to access its contents
	
	if ((inputFd = fopen(fileName, "r")) == NULL) 
		perror("Failed to open file!");
	
	int numberOfLines = GetNumberOfLines(inputFd);	// counts the number of comment lines to set the size of the variables's vectors
	int indexVectorVariables = 0;					// vectorVariables' iterator
	int indexSteppedVariables = 0;					// steppedVariables' iterator
	
	int steppedVarsIndex = 0;
	int vectorVarsIndex = 0;
	
	int tempFilesIndex = 0;
	int tempFilesIndexHelper = 0;
	FILE *tempFiles[numberOfLines];
	
	VectorVariable vectorVariables[numberOfLines];			// vector for the vector variables
	SteppedVariable steppedVariables[numberOfLines];		// vector for the stepped variables
	
	while (fgets(line, LineSize, inputFd) != NULL)
	{
		if (strstr(strchr(line, '{'), ":") != NULL)
		{
			steppedVariables[indexSteppedVariables] = (SteppedVariable)
			{
				.preffix = "\0",
				.start = 0,
				.end = 0,
				.step = 0,
				.suffix = "\0"
			};
			
			GetRangeFromLine(line, &steppedVariables[indexSteppedVariables++]);
		}
		else
		{
			vectorVariables[indexVectorVariables] = (VectorVariable)
			{
				.preffix = "\0",
				.values = { "\0" },
				.suffix = "\0",
				.numberOfValues = 0
			};
			
			GetVectorFromLine(line, &vectorVariables[indexVectorVariables++]);
		}
	}
	
	if (fclose(inputFd))
		perror("Failed to close file!");
	
	while (vectorVarsIndex < indexVectorVariables)
	{
		tempFiles[tempFilesIndex++] = CreateVectorStructure(&vectorVariables[vectorVarsIndex]);
		vectorVarsIndex++;
	}
	
	while (steppedVarsIndex < indexSteppedVariables)
	{
		tempFiles[tempFilesIndex++] = CreateSteppedStructure(&steppedVariables[steppedVarsIndex]);
		steppedVarsIndex++;
	}
	
	int fileIsEmpty = 1;
	char outputFileName[strlen(fileName) + 10];		// sums the quantities of characters in the file name and in "_alters.sp"
	
	strcpy(outputFileName, fileName);
	strcat(outputFileName, "_alters.sp");
	
	while (tempFilesIndexHelper < tempFilesIndex)
	{
		FillOutFile(tempFiles[tempFilesIndexHelper++], outputFileName, fileIsEmpty);
		fileIsEmpty = 0;
	}
}
Example #4
0
/**
 * qla2x00_rsnn_nn() - SNS Register Symbolic Node Name (RSNN_NN) of the HBA.
 * @ha: HA context
 *
 * Returns 0 on success.
 */
int
qla2x00_rsnn_nn(scsi_qla_host_t *ha)
{
	int		rval;
	uint8_t		*snn;
	uint8_t		version[20];

	ms_iocb_entry_t	*ms_pkt;
	struct ct_sns_req	*ct_req;
	struct ct_sns_rsp	*ct_rsp;

	if (IS_QLA2100(ha) || IS_QLA2200(ha)) {
		DEBUG2(printk("scsi(%ld): RSNN_ID call unsupported on "
		    "ISP2100/ISP2200.\n", ha->host_no));
		return (QLA_SUCCESS);
	}

	/* Issue RSNN_NN */
	/* Prepare common MS IOCB */
	/*   Request size adjusted after CT preparation */
	ms_pkt = ha->isp_ops.prep_ms_iocb(ha, 0, RSNN_NN_RSP_SIZE);

	/* Prepare CT request */
	ct_req = qla2x00_prep_ct_req(&ha->ct_sns->p.req, RSNN_NN_CMD,
	    RSNN_NN_RSP_SIZE);
	ct_rsp = &ha->ct_sns->p.rsp;

	/* Prepare CT arguments -- node_name, symbolic node_name, size */
	memcpy(ct_req->req.rsnn_nn.node_name, ha->node_name, WWN_SIZE);

	/* Prepare the Symbolic Node Name */
	/* Board type */
	snn = ct_req->req.rsnn_nn.sym_node_name;
	strcpy(snn, ha->model_number);
	/* Firmware version */
	strcat(snn, " FW:v");
	sprintf(version, "%d.%02d.%02d", ha->fw_major_version,
	    ha->fw_minor_version, ha->fw_subminor_version);
	strcat(snn, version);
	/* Driver version */
	strcat(snn, " DVR:v");
	strcat(snn, qla2x00_version_str);

	/* Calculate SNN length */
	ct_req->req.rsnn_nn.name_len = (uint8_t)strlen(snn);

	/* Update MS IOCB request */
	ms_pkt->req_bytecount =
	    cpu_to_le32(24 + 1 + ct_req->req.rsnn_nn.name_len);
	ms_pkt->dseg_req_length = ms_pkt->req_bytecount;

	/* Execute MS IOCB */
	rval = qla2x00_issue_iocb(ha, ha->ms_iocb, ha->ms_iocb_dma,
	    sizeof(ms_iocb_entry_t));
	if (rval != QLA_SUCCESS) {
		/*EMPTY*/
		DEBUG2_3(printk("scsi(%ld): RSNN_NN issue IOCB failed (%d).\n",
		    ha->host_no, rval));
	} else if (qla2x00_chk_ms_status(ha, ms_pkt, ct_rsp, "RSNN_NN") !=
	    QLA_SUCCESS) {
		rval = QLA_FUNCTION_FAILED;
	} else {
		DEBUG2(printk("scsi(%ld): RSNN_NN exiting normally.\n",
		    ha->host_no));
	}

	return (rval);
}
Example #5
0
/****************************************************************************
 * parent() : wait for "ready" from child, send signals to child, wait for
 *    child to exit and report what happened.
 ***************************************************************************/
static void parent()
{
	int term_stat;		/* child return status */
	int rv;			/* function return value */
	int sig;		/* current signal number */
	char *str;		/* string returned from read_pipe() */
	int *array;		/* pointer to sig_array returned from child */
	int fail = FALSE;	/* flag indicating test item failure */
	char big_mesg[MAXMESG * 6];	/* storage for big failure message */
	int caught_sigs;

	/* wait for "ready" message from child */
	if ((str = read_pipe(pipe_fd[0])) == NULL) {
		/* read_pipe() failed. */
		tst_brkm(TBROK, getout, "%s", mesg);
	}

	if (strcmp(str, READY) != 0) {
		/* child setup did not go well */
		tst_brkm(TBROK, getout, "%s", str);
	}

	/*
	 * send signals to child and see if it holds them
	 */

	for (sig = 1; sig < NUMSIGS; sig++) {
		if (choose_sig(sig)) {
			if (kill(pid, sig) < 0) {
				if (errno == ESRCH) {
					if (kill(pid, SIGTERM) < 0)
						tst_brkm(TBROK|TERRNO, getout,
							"kill(%d, %d) and kill(%d, SIGTERM) failed", pid, sig, pid);
					else
						tst_brkm(TBROK|TERRNO, getout,
							"kill(%d, %d) failed, but kill(%d, SIGTERM) worked", pid, sig, pid);
				} else
					tst_brkm(TBROK|TERRNO, getout, "kill(%d, %d) failed", pid, sig);
			}
		}
	}

	if (write_pipe(pipe_fd2[1], READY) < 0) {
		tst_brkm(TBROK|TERRNO, getout, "Unable to tell child to go, write to pipe failed");
	}

	/*
	 * child is now releasing signals, wait and check exit value
	 */
	if (wait(&term_stat) < 0)
		tst_brkm(TBROK|TERRNO, getout, "wait() failed");

	/* check child's signal exit value */
	if ((sig = CHILD_SIG(term_stat)) != 0)
		/* the child was zapped by a signal */
		tst_brkm(TBROK, cleanup, "Unexpected signal %d killed child", sig);

	/* get child exit value */

	rv = CHILD_EXIT(term_stat);

	switch (rv) {
	case EXIT_OK:
		/* sig_array sent back on pipe, check it out */
		if ((array = (int *)read_pipe(pipe_fd[0])) == NULL) {
			/* read_pipe() failed. */
			tst_resm(TBROK, "%s", mesg);
			break;
		}
#if DEBUG > 1
		for (sig = 1; sig < NUMSIGS; sig++) {
			printf("array[%d] = %d\n", sig, array[sig]);
		}
#endif
		caught_sigs = 0;
		for (sig = 1; sig < NUMSIGS; sig++) {
			if (choose_sig(sig)) {
				if (array[sig] != 1) {
					/* sig was not caught or caught too many times */
					(void)sprintf(mesg,
						      "\tsignal %d caught %d times (expected 1).\n",
						      sig, array[sig]);
					(void)strcat(big_mesg, mesg);
					fail = TRUE;
				} else {
					caught_sigs++;
				}
			}
		}		/* endfor */

		if (fail == TRUE)
			tst_resm(TFAIL, "%s", big_mesg);
		else
			tst_resm(TPASS,
				 "sigrelse() released all %d signals under test.",
				 caught_sigs);
		break;

	case TBROK:
		/* get BROK message from pipe */
		if ((str = read_pipe(pipe_fd[0])) == NULL) {
			/* read_pipe() failed. */
			tst_resm(TBROK, "%s", mesg);
			break;
		}

		/* call tst_res: str contains the message */
		tst_resm(TBROK, "%s", str);
		break;
	case SIG_CAUGHT:
		/* a signal was caught before it was released */
		tst_resm(TBROK, "A signal was caught before being released.");
		break;
	case WRITE_BROK:
		/* the write() call failed in child's write_pipe */
		tst_resm(TBROK, "write() pipe failed for child.");
		break;
	case HANDLE_ERR:
		/* more than one signal tried to be handled at the same time */
		tst_resm(TBROK, "Error occured in signal handler.");
		break;
	default:
		tst_resm(TBROK, "Unexpected exit code %d from child", rv);
		break;
	}

}				/* end of parent */
Example #6
0
//*********************************************************
int server(void)
{
	struct sockaddr_in monadr, sonadr;
	int fd, opt=1, taille;
	int serv_sock, client_sock;
   int nb_lu;	
	int nfds;
	fd_set rfds, afds;
	int error;
	
	char message[20]="";
	char response[20]="";
	
	MyLog("Create server ...\n");
	serv_sock = socket(PF_INET, SOCK_STREAM, 0);
	setsockopt(serv_sock, SOL_SOCKET, SO_REUSEADDR,(char *) &opt, sizeof(opt));
	
	/* init socket serveur */
	bzero( (char *)&monadr, sizeof monadr);
	monadr.sin_family = AF_INET;
	monadr.sin_port = htons(PORT);
	monadr.sin_addr.s_addr = INADDR_ANY;

	if( bind(serv_sock, (struct sockaddr *)&monadr, sizeof(monadr)) == -1 ) {
		return(1);
	}

	if( listen(serv_sock, MAXCONN) == -1 ) {
		return(1);
	}
	
	/* init sockets list*/
	nfds = getdtablesize();
	FD_ZERO(&afds);
	FD_SET(serv_sock, &afds);

	/* gestion des clients */
	while(!Terminated) 
	{
		memcpy(&rfds, &afds, sizeof(rfds));
		if( select(nfds, &rfds, 0, 0, 0) == -1 ) 
			{/* signaux non bloquants */
				if( errno == EINTR ) continue;
				return(1);
			}
		if( FD_ISSET(serv_sock, &rfds) ) /* New connection ?*/
			{
				taille = sizeof sonadr;
				if( (client_sock = accept(serv_sock, (struct sockaddr *)&sonadr,(socklen_t *)&taille)) == -1 ) 
					{
						return(1);
					}
				//syslog(LOG_NOTICE,"client connection from %s \n", inet_ntoa(sonadr.sin_addr));
				fflush(stdout);
				FD_SET(client_sock, &afds);
				fcntl(client_sock, F_SETFL, O_NONBLOCK | fcntl(client_sock, F_GETFL, 0));
			}
		/* Tester si les sockets clientes ont boug�s */
		for( fd=0; fd<nfds; fd++ ) {
			if( fd != serv_sock && FD_ISSET(fd, &rfds) ) {
				/* traiter le client */
				strcpy(message,"");
				strcpy(response,"");
				nb_lu = read(fd, message, BUFSIZE);
				//MyLog("nb_lu : %d/%d/%d\n",nb_lu,strlen(message),fd);
				if( nb_lu > 0 ) {
					message[nb_lu]='\0';
					if ((error=read_socket(message,response))!=SUCCES) {
						sprintf(response,"error :%d\n",error);
					}
					strcat(response,"\n");
					write(fd, response, strlen(response));
				} else {
					close(fd);
					FD_CLR(fd, &afds);
				}
			}
		}
	}
	return(0);
}
Example #7
0
static void
parse_input(int argc, char *argv[])
{
	int ch, foundeof;
	char **avj;

	foundeof = 0;

	switch (ch = getchar()) {
	case EOF:
		/* No arguments since last exec. */
		if (p == bbp) {
			waitchildren(*av, 1);
			exit(rval);
		}
		goto arg1;
	case ' ':
	case '\t':
		/* Quotes escape tabs and spaces. */
		if (insingle || indouble || zflag)
			goto addch;
		goto arg2;
	case '\0':
		if (zflag) {
			/*
			 * Increment 'count', so that nulls will be treated
			 * as end-of-line, as well as end-of-argument.  This
			 * is needed so -0 works properly with -I and -L.
			 */
			count++;
			goto arg2;
		}
		goto addch;
	case '\n':
		if (zflag)
			goto addch;
		count++;	    /* Indicate end-of-line (used by -L) */

		/* Quotes do not escape newlines. */
arg1:		if (insingle || indouble)
			errx(1, "unterminated quote");
arg2:
		foundeof = *eofstr != '\0' &&
		    strncmp(argp, eofstr, p - argp) == 0;

		/* Do not make empty args unless they are quoted */
		if ((argp != p || wasquoted) && !foundeof) {
			*p++ = '\0';
			*xp++ = argp;
			if (Iflag) {
				size_t curlen;

				if (inpline == NULL)
					curlen = 0;
				else {
					/*
					 * If this string is not zero
					 * length, append a space for
					 * separation before the next
					 * argument.
					 */
					if ((curlen = strlen(inpline)))
						strcat(inpline, " ");
				}
				curlen++;
				/*
				 * Allocate enough to hold what we will
				 * be holding in a second, and to append
				 * a space next time through, if we have
				 * to.
				 */
				inpline = realloc(inpline, curlen + 2 +
				    strlen(argp));
				if (inpline == NULL)
					errx(1, "realloc failed");
				if (curlen == 1)
					strcpy(inpline, argp);
				else
					strcat(inpline, argp);
			}
		}

		/*
		 * If max'd out on args or buffer, or reached EOF,
		 * run the command.  If xflag and max'd out on buffer
		 * but not on args, object.  Having reached the limit
		 * of input lines, as specified by -L is the same as
		 * maxing out on arguments.
		 */
		if (xp == endxp || p > ebp || ch == EOF ||
		    (Lflag <= count && xflag) || foundeof) {
			if (xflag && xp != endxp && p > ebp)
				errx(1, "insufficient space for arguments");
			if (jfound) {
				for (avj = argv; *avj; avj++)
					*xp++ = *avj;
			}
			prerun(argc, av);
			if (ch == EOF || foundeof) {
				waitchildren(*av, 1);
				exit(rval);
			}
			p = bbp;
			xp = bxp;
			count = 0;
		}
		argp = p;
		wasquoted = 0;
		break;
	case '\'':
		if (indouble || zflag)
			goto addch;
		insingle = !insingle;
		wasquoted = 1;
		break;
	case '"':
		if (insingle || zflag)
			goto addch;
		indouble = !indouble;
		wasquoted = 1;
		break;
	case '\\':
		if (zflag)
			goto addch;
		/* Backslash escapes anything, is escaped by quotes. */
		if (!insingle && !indouble && (ch = getchar()) == EOF)
			errx(1, "backslash at EOF");
		/* FALLTHROUGH */
	default:
addch:		if (p < ebp) {
			*p++ = ch;
			break;
		}

		/* If only one argument, not enough buffer space. */
		if (bxp == xp)
			errx(1, "insufficient space for argument");
		/* Didn't hit argument limit, so if xflag object. */
		if (xflag)
			errx(1, "insufficient space for arguments");

		if (jfound) {
			for (avj = argv; *avj; avj++)
				*xp++ = *avj;
		}
		prerun(argc, av);
		xp = bxp;
		cnt = ebp - argp;
		memcpy(bbp, argp, (size_t)cnt);
		p = (argp = bbp) + cnt;
		*p++ = ch;
		break;
	}
}
Example #8
0
static void shaderFilePath(char* _out, const char* _name)
{
	strcpy(_out, s_shaderPath);
	strcat(_out, _name);
	strcat(_out, ".bin");
}
Example #9
0
File: radio.c Project: nesl/sos-2x
void sim_radio_init()
{
	//! initialize node id and location
	FILE *fid;
	char line_buf[LINE_BUF_SIZE];    // line buffer
	int j = 0;

	if((fid = fopen(topofile, "r")) == NULL){
		char* sosrootdir;
		char newtopofile[256];
		sosrootdir = getenv("SOSROOT");
		strcpy(newtopofile, sosrootdir);
		printf("Unable to open %s\n", topofile);
		strcat(newtopofile, "/platform/sim/topo.def\0");
		if((fid = fopen(newtopofile, "r")) == NULL){
			printf("Unable to open %s\n", newtopofile);
			exit(1);
		}
		else
			topofile = newtopofile;
	}
	printf("Using topology file %s\n", topofile);
	// remove comments
	do{
		fgets(line_buf, LINE_BUF_SIZE, fid);
	} while(line_buf[0] == '#');

	if(sscanf(line_buf, "%d", &totalNodes) != 1){
		fprintf(stderr, "no data in %s\n", topofile);
		exit(1);
	}

	topo_array = (Topology*)malloc((totalNodes + 1) * sizeof(Topology));
	if (topo_array == NULL){
		fprintf(stderr, "not enough memory\n");
		exit(1);
	}

	for(j = 0; j < totalNodes; j++){
		do{
			// remove comments
			fgets(line_buf, LINE_BUF_SIZE, fid);
		}while(line_buf[0] == '#');
		if(sscanf(line_buf, "%d %d %d %d %d %u",
					&topo_array[j].id,
					&topo_array[j].unit,
					&topo_array[j].x,
					&topo_array[j].y,
					&topo_array[j].z,
					&topo_array[j].r2) != 6){
			fprintf(stderr, "not enough definitions in %s: %s\n", topofile, line_buf);
			exit(1);
		}
		//topo_array[j].id = j;
		topo_array[j].type = TOPO_TYPE_OTHER;
		topo_array[j].sock = -1;
	}
#if 0
	print_nodes();
	exit(1);
#endif
	if(fclose(fid) != 0){
		perror("fclose");
		exit(1);
	}

	// finding node id by finding available port
	//for(j = 1; j <= totalNodes; j++)
	{
		int sock;
		int myj = getj(ker_id());
		struct sockaddr_in name;
		sock = socket(AF_INET, SOCK_DGRAM, 0);

		if (sock < 0) {
			perror("opening datagram socket");
			exit(1);
		}

		/* Create name with wildcards. */
		name.sin_family = AF_INET;
		name.sin_addr.s_addr = INADDR_ANY;
		//		name.sin_port = htons(20000 + ker_id());
		name.sin_port = htons( get_sin_port(ker_id()) );

		if (bind(sock, (struct sockaddr *)&name, sizeof(name)) == 0) {
			//node_address = j;
			// successfully get an id
			topo_array[myj].sock = sock;
			topo_array[myj].type = TOPO_TYPE_SELF;
			topo_self = topo_array[myj];
			//! assign sos_info
			node_loc.x = topo_self.x;
			node_loc.y = topo_self.y;
			node_loc.z = topo_self.z;
			node_loc.unit = topo_self.unit;
		}else{
			fprintf(stderr, "Unable to allocate UDP for this node!\n");
			fprintf(stderr, "Perhaps you are using the same node ID\n");
			fprintf(stderr, "Use -n <node address> to specify different address\n\n");
			exit(1);
		}
	}
	{
		uint16_t id;
		node_loc_t self;
		id = ker_id();
		self = ker_loc();
		if((id != topo_self.id) || (self.x != topo_self.x) ||
				(self.y != topo_self.y) || (self.z != topo_self.z) ||
				(self.unit != topo_self.unit)){
			fprintf(stderr, "topo file and self settings do not agree.\n");
			fprintf(stderr, "ker_id() = %d : topo_self.id = %d\n",
					id, topo_self.id);
			fprintf(stderr, "self.unit = %d : topo_self.unit = %d\n",
					self.unit, topo_self.unit);
			fprintf(stderr, "self.x = %d : topo_self.x = %d\n",
					self.x, topo_self.x);
			fprintf(stderr, "self.y = %d : topo_self.y = %d\n",
					self.y, topo_self.y);
			fprintf(stderr, "self.z = %d : topo_self.z = %d\n",
					self.z, topo_self.z);
			exit(1);
		}
	}

	for(j = 0; j < totalNodes; j++){
		uint32_t r2;
		uint16_t id;
		node_loc_t self, neighbor;
		id = ker_id();
		self = ker_loc();
		if(topo_array[j].type == TOPO_TYPE_SELF) continue;
		neighbor.unit = topo_array[j].unit;
		neighbor.x = topo_array[j].x;
		neighbor.y = topo_array[j].y;
		neighbor.z = topo_array[j].z;
		r2 = ker_loc_r2(&self,&neighbor);
		if(r2 < 0){
			fprintf(stderr, "units for neighbor do not agree.\n");
			fprintf(stderr, "self.unit = %d : neighbor.unit = %d.\n",
					self.unit, neighbor.unit);
			exit(1);
		}
		DEBUG("neighbor %d r2 = %d, self r2 = %d\n", topo_array[j].id, r2, topo_self.r2);
		if(r2 <= topo_self.r2){
			topo_array[j].type = TOPO_TYPE_NEIGHBOR;
			DEBUG("node %d is reachable\n", topo_array[j].id);
		}
	}
	{
		struct hostent	*hostptr;
		char theHost [MAXLENHOSTNAME];
		unsigned long hostaddress;

		/* find out who I am */

		if ((gethostname(theHost, MAXLENHOSTNAME))<0) {
			perror ("could not get hostname");
			exit(1);
		}
		//DEBUG("-- found host name = %s\n", theHost);

		if ((hostptr = gethostbyname (theHost)) == NULL) {
			perror ("could not get host by name, use 127.0.0.1");
			if(( hostptr = gethostbyname ("127.0.0.1") ) == NULL ) {
				perror ("Cannot get host 127.0.0.1");
				exit(1);
			}

		}
		hostaddress = *((unsigned long *) hostptr->h_addr);

		/* init the address structure */
		sockaddr.sin_family    	= AF_INET;
		sockaddr.sin_port		= htons( get_sin_port(ker_id()) );
		sockaddr.sin_addr.s_addr 	= hostaddress;
	}
	//! assign locations
	//node_loc.x = (uint16_t)(topo_self.x);
	//node_loc.y = (uint16_t)(topo_self.y);
	//print_nodes();
}
Example #10
0
/*
 * Apply codes in writer command:
 * %w -> "where"
 * %r -> "replace"
 *
 * Replace:
 * 'always' => 'a', chr(97)
 * 'ifnewer' => 'w', chr(119)
 * 'ifolder' => 'o', chr(111)
 * 'never' => 'n', chr(110)
 *
 * This function will allocate the required amount of memory with malloc.
 * Need to be free()d manually.
 *
 * Inspired by edit_job_codes in lib/util.c
 */
static char *apply_rp_codes(bpContext *ctx)
{
   char add[10];
   const char *str;
   char *p, *q, *omsg, *imsg;
   int w_count = 0, r_count = 0;
   struct plugin_ctx *p_ctx = (struct plugin_ctx *)ctx->pContext;

   if (!p_ctx) {
      return NULL;
   }

   imsg = p_ctx->writer;
   if (!imsg) {
      return NULL;
   }

   if ((p = imsg)) {
      while ((q = strstr(p, "%w"))) {
         w_count++;
         p=q+1;
      }

      p = imsg;
      while ((q = strstr(p, "%r"))) {
         r_count++;
         p=q+1;
      }
   }

   /*
    * Required mem:
    * len(imsg)
    * + number of "where" codes * (len(where)-2)
    * - number of "replace" codes
    */
   omsg = (char*)malloc(strlen(imsg) + (w_count * (strlen(p_ctx->where)-2)) - r_count + 1);
   if (!omsg) {
      Jmsg(ctx, M_FATAL, "bpipe-fd: Out of memory.");
      return NULL;
   }

   *omsg = 0;
   for (p=imsg; *p; p++) {
      if (*p == '%') {
         switch (*++p) {
         case '%':
            str = "%";
            break;
         case 'w':
             str = p_ctx->where;
             break;
         case 'r':
            snprintf(add, 2, "%c", p_ctx->replace);
            str = add;
            break;
         default:
            add[0] = '%';
            add[1] = *p;
            add[2] = 0;
            str = add;
            break;
         }
      } else {
         add[0] = *p;
         add[1] = 0;
         str = add;
      }
      strcat(omsg, str);
   }
   return omsg;
}
Example #11
0
	/* public c'tors */
	compare_fails_exception(const char* msg) {	
		strncpy(mywhat,msg,MAX_ERR_LEN-1);
		strcat(mywhat,"\n");
	}
Example #12
0
/*
	This is the threaded function. It is called after a good connection has been made.
	It parses the header and deteremines the proper response that needs to be sent 
	from the server in the correct format. It responds in both 1.0 and 1.1 HTTP requests.
	

*/
void * echo(void * connfd)
{
		
	myStruct *arg = (myStruct *) connfd;//gets the argument from the void pointer
	int fd = arg->s;//gets the file descriptor
	//declare storage char arrays
	char method[1024], uri[8192], version[1024];
	char buf[8192];
	//clear the char arrays
	memset(buf, '\0', sizeof(buf));
	memset(method, '\0', sizeof(method));
	memset(uri, '\0', sizeof(uri));
	memset(version, '\0', sizeof(version));

	rio_t rio;
	//connection the rio the the fd and then read
	Rio_readinitb(&rio, fd);
	Rio_readlineb(&rio, buf, 8192);
	//gets the methods, uri, version
	sscanf(buf, "%s %s %s", method, uri, version);
	//make sure it is a get request
	if (strcasecmp(method, "GET") == 0)
	{		
		//search for the file of the request
		FILE *file; 
		
		char filetype[100];
		char * type;
		int position = -1;
		int current = 100;
		int count = 4;
		//gets the extensio
		//get the file type in a very slow way
		for(current = 100; current != 0; current--)
		{
			if (uri[current] == '.' && position == -1)
			{
				position = current;
				break;
			}
			else 
				filetype[count] = uri[current];
			count++;
		}
		//get the correct mime type
		if (strstr(filetype, "html") == 0 || strstr(filetype, "htm") == 0)
			type = "text/html";
		else if (strstr(filetype, "jpg") == 0)
			type = "image/jpeg";
		else if (strstr(filetype, "js") == 0)
			type = "text/javascript";
		else if (strstr(filetype, "gif") == 0)
			type = "image/gif";
		else if (strstr(filetype, "txt") == 0)
			type = "text/plain";
		else if (strstr(filetype, "css") == 0)
			type = "text/css";
		else if (strstr(filetype, "ram") == 0 || strstr(filetype, "ra") == 0)
			type = "audio/x-pn-realaudio";
		else 
			type = "text/plain";
			
		char status[100];
		//format correctly
		if (strstr(uri, "HTTP/1.1") != NULL)	
			strcpy(status, "HTTP/1.1");
		else 
			strcpy(status, "HTTP/1.0");
			
		char body[8192];//used to store the body of the request in all but opening binary files
		
		//if it is a junk file in any way
		if (strstr(uri, "junk") != NULL)
		{
			//returns 404 not found error
			if (strcmp(version, "HTTP/1.0"))
				strcat(body, "HTTP/1.0 404 Not Found");
			else 
				strcat(body, "HTTP/1.1 404 Not Found");
			send(fd, body, strlen(body), 0);
		}
		//one of the checks
		else if (strstr(uri, "meminfo?callback=") != NULL)
		{
			//parses the request for the callback name and
			//then returns meminfo with the name formatting.
			char argument[100];
			char * position = strchr(uri, '=');
			position++;
			
			strcpy(argument, position);
			int y;
			int x = 0;
			for (y = 0; y < 100; y++)
				if((argument[y] == '&' || argument[y] =='_' || argument[y] == '=') && x != 1)
				{
					argument[y] = '\0';
					y = 100;
					x = 1;
				}
			strcat(body, argument);
			strcat(body, "(");
			#include "json_mem_info.c"
			strcat(body, ")");
			send(fd, body, strlen(body), 0);
		}
		//other check
		else if (strstr(uri, "/meminfo?") != NULL && strstr(uri, "&callback=") != NULL)
		{
			//parses the request for the callback name and
			//then returns meminfo with the name formatting.
			
			char argument[8192];
			char * position = strstr(uri, "&callback=");
			position += 10;
			strcpy(argument, position);
			int a;
			int n = 0;
			//checks for random ascii characters
			for (a = 0; a < 8192; a++)
			{
				if((argument[a] == '&' || argument[a] =='_' || argument[a] == '=') && n != 1)
				{
					argument[a] = '\0';
					a = 100;
					n = 1;	
				}
			}
			strcat(body, argument);
			strcat(body, "(");
			#include "json_mem_info.c" 
			strcat(body, ")");
			send(fd, body, strlen(body), 0);//sends the information
		}
		//default meminfo
		else if (strncmp(uri, "/meminfo", 8) == 0)
		{
			#include "json_mem_info.c"
			fclose(file);
			send(fd, body, strlen(body), 0);
		}		
		else if (strstr(uri, "loadavg?callback=") != NULL )
		{
			//the loadavg call, parses the uri to get the correct name
			char argument[8192];
			char * position = strchr(uri, '=');
			position++;
			strcpy(argument, position);
			int a;
			int n = 0;
			for (a = 0; a < 8192; a++)
			{
				if((argument[a] == '&' || argument[a] =='_' || argument[a] == '=') && n != 1)
				{
					argument[a] = '\0';
					a = 100;
					n = 1;
				}
			}
			strcat(body, argument);
			strcat(body, "(");
			#include "json_loadavg.c"
			strcat(body, ")");
			send(fd, body, strlen(body), 0);
		}
		else if (strstr(uri, "/loadavg?") != NULL && strstr(uri, "&callback=") != NULL)
		{
			//the most complicated loadvg callback
			char argument[8192];
			char * position = strstr(uri, "&callback=");
			position += 10;
			strcpy(argument, position);
			int a;
			int n = 0;
			for (a = 0; a < 8192; a++)
			{
				if((argument[a] == '&' || argument[a] =='_' || argument[a] == '=') && n != 1)
				{
					argument[a] = '\0';
					a = 100;
					n = 1;
					
				}
			}
			strcat(body, argument);
			strcat(body, "(");
			#include "json_loadavg.c"
			strcat(body, ")");
			send(fd, body, strlen(body), 0);
		}
		else if (strstr(uri, "/loadavg") != NULL)
		{
			//the basic loadavg
			//1.0 or 1.1
			if (strcmp(version, "HTTP/1.0") == 0)
			{
				strcat(body, "HTTP/1.0 200 OK\r\n\r\n");
			}
			#include "json_loadavg.c"
			fclose(file);

			send(fd, body, strlen(body), 0);
		}
		//this calls the runloop functionality
		else if (strstr(uri, "runloop") != NULL){
			#include "runloop.c"
		}
		//this calls the allocanon functionality
		else if (strstr(uri, "allocanon") != NULL){
			#include "allocanon.c"
		}
		//this calls the freeanon functionality
		else if (strstr(uri, "freeanon") != NULL){
			#include "freeanon.c"
		}
		else 
		{	
			//when the request is not a predifined request. Checks if the file 
			//exists based on the uri. If it does it reads it. If it doesnt
			//it returns 404 not found
			//check if its a file
			int p;
			for(p = 1; p < strlen(uri)+1; p++)
			{
				uri[p-1] = uri[p];
			}
			//the file
			if (path != NULL)
			{
				strcpy(uri, strcat(path, uri));
			}
			file = fopen(uri, "r");
			if (file != NULL)
			{
				//when the file exists it gets the proper header based on the content type and
				//length and the request
				char header[100];
				char length[100];
				char typeH[100];
				char * sent;
				
				strcat(header, version);
				strcat(header, " 200 OK\r\n");
				strcat(typeH, "Content-Type: ");
				strcat(typeH, type);
				strcat(typeH, "\r\n");
				
				strcat(length, "Content-Length: ");
				//this gets the files length and then reads the file and stores it
				fseek(file, 0, SEEK_END);
				int size = ftell(file);
				fseek(file, 0, SEEK_SET);
				sent = (char *) malloc(size);
				fread(sent, size, 1, file);

				strcat(length, "\r\n\r\n");
				//sends the header, content type, content header and the binary file
				send(fd, header, strlen(header), 0);
				send(fd, typeH, strlen(typeH), 0);
				send(fd, length, strlen(length), 0);
				send(fd, sent, size, 0);
				fclose(file);
			}
			else 
			{
				//when the file does not exist
				if (strcmp(version, "HTTP/1.0"))
					strcat(body, "HTTP/1.0 404 Not Found");
				else 
					strcat(body, "HTTP/1.1 404 Not Found");
				send(fd, body, strlen(body), 0);				
			}
		}
	}
	else 
	{
		//when the method is not recognized
		send(fd, "HTTP/1.1 405 Method Not Allowed", strlen("HTTP/1.1 405 Method Not Allowed"), 0);
	}
	close (fd);
	pthread_exit(NULL);
}
int main() {
    void *lib;
    void *lib_struct;
    
    // declaration for the external functions used
    void *(*init)(const char *);
    void (*free)();
    uint64_t (*get_ahash)(void *, const char *);
    uint64_t (*get_dhash)(void *, const char *);
    uint64_t (*get_phash)(void *, const char *);

    //test image locations
    static const char image1PathStr[] = u8"../test_images/sample_01_";
    static const char image2PathStr[] = u8"../test_images/sample_02_";
    static const char image3PathStr[] = u8"../test_images/sample_03_";
    static const char image4PathStr[] = u8"../test_images/sample_04_";
    
    // Array of pointers to the base image paths to test
    //static const char *imagesSet[] = { image1PathStr, image2PathStr, image3PathStr };
    static const char *imagesSet[] = { image1PathStr, image2PathStr, image3PathStr, image4PathStr };
    static const int imageSetSize = 4;

    // designators for the image sizes
    static const char largeImageSizeStr[] = u8"large";
    static const char mediumImageSizeStr[] = u8"medium";
    static const char smallImageSizeStr[] = u8"small";

    // Array of pointers to the images sizes
    static const char *imageSizesSet[] = { largeImageSizeStr, mediumImageSizeStr, smallImageSizeStr };
    static int imageSizesSetSize = 3;

    // Image extension
    static const char imageExtensionStr[] = u8".jpg";

    // Loading the external library
    lib = dlopen("./libpihash.so", RTLD_LAZY);

    //Registering the external functions
    *(void **)(&init) = dlsym(lib,"ext_init");
    *(void **)(&free) = dlsym(lib,"ext_free");
    *(void **)(&get_ahash) = dlsym(lib,"ext_get_ahash");
    *(void **)(&get_dhash) = dlsym(lib,"ext_get_dhash");
    *(void **)(&get_phash) = dlsym(lib,"ext_get_phash");

    // Init the shared library
    lib_struct = init(u8"./.hash_cache");

    //temp buffer for the path
    char *imagePathBuffer = malloc(100);
    // loop over the images and sizes to test
    for (int i = 0; i < imageSetSize; i++) {
        for (int j = 0; j < imageSizesSetSize; j++) {
            // Make sure the buffer is clean before using it
            memset(imagePathBuffer,0,100);
            // Getting the correct path
            strcat(imagePathBuffer, imagesSet[i]);
            strcat(imagePathBuffer, imageSizesSet[j]);
            strcat(imagePathBuffer, imageExtensionStr);
            //printf("Path: %s\n", imagePath);
            
            // Visually proving that the bytes stored are the correct representation
            //print_ustr_bytes(imagePath);
            printf("Image: %s\n",imagePathBuffer);

            // Printing information about the hashes of the provided images
            uint64_t imageAhash = get_ahash(lib_struct, imagePathBuffer);
            uint64_t imageDhash = get_dhash(lib_struct, imagePathBuffer);
            uint64_t imagePhash = get_phash(lib_struct, imagePathBuffer);
            
            printf("ahash: %llu \n", imageAhash);
            printf("dhash: %llu \n", imageDhash);
            printf("phash: %llu \n", imagePhash);
        }
    } 
    //cleanup and close the buffer
    memset(imagePathBuffer,0,100);
    free(imagePathBuffer);

    // Closing the shared library reference
    if (lib != NULL ) dlclose(lib);
    return EXIT_SUCCESS;
}
Example #14
0
int show_basic_mii(int sock, int phy_id)
{
    char buf[100];
    int i, mii_val[32];
    int bmcr, bmsr, advert, lkpar;

    /* Some bits in the BMSR are latched, but we can't rely on being
       the only reader, so only the current values are meaningful */
    mdio_read(sock, MII_BMSR);
    for (i = 0; i < ((verbose > 1) ? 32 : 8); i++)
	mii_val[i] = mdio_read(sock, i);

    if (mii_val[MII_BMCR] == 0xffff) {
	fprintf(stderr, "  No MII transceiver present!.\n");
	return -1;
    }

    /* Descriptive rename. */
    bmcr = mii_val[MII_BMCR]; bmsr = mii_val[MII_BMSR];
    advert = mii_val[MII_ANAR]; lkpar = mii_val[MII_ANLPAR];

    sprintf(buf, "%s: ", ifr.ifr_name);
    if (bmcr & MII_BMCR_AN_ENA) {
	if (bmsr & MII_BMSR_AN_COMPLETE) {
	    if (advert & lkpar) {
		strcat(buf, (lkpar & MII_AN_ACK) ?
		       "negotiated" : "no autonegotiation,");
		strcat(buf, media_list(advert & lkpar, 1));
		strcat(buf, ", ");
	    } else {
		strcat(buf, "autonegotiation failed, ");
	    }
	} else if (bmcr & MII_BMCR_RESTART) {
	    strcat(buf, "autonegotiation restarted, ");
	}
    } else {
	sprintf(buf+strlen(buf), "%s Mbit, %s duplex, ",
	       (bmcr & MII_BMCR_100MBIT) ? "100" : "10",
	       (bmcr & MII_BMCR_DUPLEX) ? "full" : "half");
    }
    strcat(buf, (bmsr & MII_BMSR_LINK_VALID) ? "link ok" : "no link");

    if (opt_watch) {
	if (opt_log) {
	    syslog(LOG_INFO, buf);
	} else {
	    char s[20];
	    time_t t = time(NULL);
	    strftime(s, sizeof(s), "%T", localtime(&t));
	    printf("%s %s\n", s, buf);
	}
    } else {
	printf("%s\n", buf);
    }

    if (verbose > 1) {
	printf("  registers for MII PHY %d: ", phy_id);
	for (i = 0; i < 32; i++)
	    printf("%s %4.4x", ((i % 8) ? "" : "\n   "), mii_val[i]);
	printf("\n");
    }

    if (verbose) {
	printf("  product info: ");
	for (i = 0; i < NMII; i++)
	    if ((mii_id[i].id1 == mii_val[2]) &&
		(mii_id[i].id2 == (mii_val[3] & 0xfff0)))
		break;
	if (i < NMII)
	    printf("%s rev %d\n", mii_id[i].name, mii_val[3]&0x0f);
	else
	    printf("vendor %02x:%02x:%02x, model %d rev %d\n",
		   mii_val[2]>>10, (mii_val[2]>>2)&0xff,
		   ((mii_val[2]<<6)|(mii_val[3]>>10))&0xff,
		   (mii_val[3]>>4)&0x3f, mii_val[3]&0x0f);
	printf("  basic mode:   ");
	if (bmcr & MII_BMCR_RESET)
	    printf("software reset, ");
	if (bmcr & MII_BMCR_LOOPBACK)
	    printf("loopback, ");
	if (bmcr & MII_BMCR_ISOLATE)
	    printf("isolate, ");
	if (bmcr & MII_BMCR_COLTEST)
	    printf("collision test, ");
	if (bmcr & MII_BMCR_AN_ENA) {
	    printf("autonegotiation enabled\n");
	} else {
	    printf("%s Mbit, %s duplex\n",
		   (bmcr & MII_BMCR_100MBIT) ? "100" : "10",
		   (bmcr & MII_BMCR_DUPLEX) ? "full" : "half");
	}
	printf("  basic status: ");
	if (bmsr & MII_BMSR_AN_COMPLETE)
	    printf("autonegotiation complete, ");
	else if (bmcr & MII_BMCR_RESTART)
	    printf("autonegotiation restarted, ");
	if (bmsr & MII_BMSR_REMOTE_FAULT)
	    printf("remote fault, ");
	printf((bmsr & MII_BMSR_LINK_VALID) ? "link ok" : "no link");
	printf("\n  capabilities:%s", media_list(bmsr >> 6, 0));
	printf("\n  advertising: %s", media_list(advert, 0));
	if (lkpar & MII_AN_ABILITY_MASK)
	    printf("\n  link partner:%s", media_list(lkpar, 0));
	printf("\n");
    }
    return 0;
}
Example #15
0
// Split from the basic MakePet to allow backward compatiblity with existing code while also
// making it possible for petpower to be retained without the focus item having to
// stay equipped when the character zones. petpower of -1 means that the currently equipped petfocus
// of a client is searched for and used instead.
void Mob::MakePoweredPet(uint16 spell_id, const char* pettype, int16 petpower,
		const char *petname, float in_size) {
	// Sanity and early out checking first.
	if(HasPet() || pettype == nullptr)
		return;

	int16 act_power = 0; // The actual pet power we'll use.
	if (petpower == -1) {
		if (this->IsClient()) {
			act_power = CastToClient()->GetFocusEffect(focusPetPower, spell_id);//Client only
			act_power = CastToClient()->mod_pet_power(act_power, spell_id);
		}
#ifdef BOTS
		else if (this->IsBot())
			act_power = CastToBot()->GetBotFocusEffect(Bot::BotfocusPetPower, spell_id);
#endif
	}
	else if (petpower > 0)
		act_power = petpower;

	// optional rule: classic style variance in pets. Achieve this by
	// adding a random 0-4 to pet power, since it only comes in increments
	// of five from focus effects.

	//lookup our pets table record for this type
	PetRecord record;
	if(!database.GetPoweredPetEntry(pettype, act_power, &record)) {
		Message(13, "Unable to find data for pet %s", pettype);
		Log.Out(Logs::General, Logs::Error, "Unable to find data for pet %s, check pets table.", pettype);
		return;
	}

	//find the NPC data for the specified NPC type
	const NPCType *base = database.LoadNPCTypesData(record.npc_type);
	if(base == nullptr) {
		Message(13, "Unable to load NPC data for pet %s", pettype);
		Log.Out(Logs::General, Logs::Error, "Unable to load NPC data for pet %s (NPC ID %d), check pets and npc_types tables.", pettype, record.npc_type);
		return;
	}

	//we copy the npc_type data because we need to edit it a bit
	NPCType *npc_type = new NPCType;
	memcpy(npc_type, base, sizeof(NPCType));

	// If pet power is set to -1 in the DB, use stat scaling
	if ((this->IsClient() 
#ifdef BOTS
		|| this->IsBot()
#endif
		) && record.petpower == -1)
	{
		float scale_power = (float)act_power / 100.0f;
		if(scale_power > 0)
		{
			npc_type->max_hp *= (1 + scale_power);
			npc_type->cur_hp = npc_type->max_hp;
			npc_type->AC *= (1 + scale_power);
			npc_type->level += 1 + ((int)act_power / 25) > npc_type->level + RuleR(Pets, PetPowerLevelCap) ? RuleR(Pets, PetPowerLevelCap) : 1 + ((int)act_power / 25); // gains an additional level for every 25 pet power
			npc_type->min_dmg = (npc_type->min_dmg * (1 + (scale_power / 2)));
			npc_type->max_dmg = (npc_type->max_dmg * (1 + (scale_power / 2)));
			npc_type->size = npc_type->size * (1 + (scale_power / 2)) > npc_type->size * 3 ? npc_type->size * 3 : (1 + (scale_power / 2));
		}
		record.petpower = act_power;
	}

	//Live AA - Elemental Durability
	int16 MaxHP = aabonuses.PetMaxHP + itembonuses.PetMaxHP + spellbonuses.PetMaxHP;

	if (MaxHP){
		npc_type->max_hp += (npc_type->max_hp*MaxHP)/100;
		npc_type->cur_hp = npc_type->max_hp;
	}

	//TODO: think about regen (engaged vs. not engaged)

	// Pet naming:
	// 0 - `s pet
	// 1 - `s familiar
	// 2 - `s Warder
	// 3 - Random name if client, `s pet for others
	// 4 - Keep DB name


	if (petname != nullptr) {
		// Name was provided, use it.
		strn0cpy(npc_type->name, petname, 64);
	} else if (record.petnaming == 0) {
		strcpy(npc_type->name, this->GetCleanName());
		npc_type->name[25] = '\0';
		strcat(npc_type->name, "`s_pet");
	} else if (record.petnaming == 1) {
		strcpy(npc_type->name, this->GetName());
		npc_type->name[19] = '\0';
		strcat(npc_type->name, "`s_familiar");
	} else if (record.petnaming == 2) {
		strcpy(npc_type->name, this->GetName());
		npc_type->name[21] = 0;
		strcat(npc_type->name, "`s_Warder");
	} else if (record.petnaming == 4) {
		// Keep the DB name
	} else if (record.petnaming == 3 && IsClient()) {
		strcpy(npc_type->name, GetRandPetName());
	} else {
		strcpy(npc_type->name, this->GetCleanName());
		npc_type->name[25] = '\0';
		strcat(npc_type->name, "`s_pet");
	}

	//handle beastlord pet appearance
	if(record.petnaming == 2)
	{
		switch(GetBaseRace())
		{
		case VAHSHIR:
			npc_type->race = TIGER;
			npc_type->size *= 0.8f;
			break;
		case TROLL:
			npc_type->race = ALLIGATOR;
			npc_type->size *= 2.5f;
			break;
		case OGRE:
			npc_type->race = BEAR;
			npc_type->texture = 3;
			npc_type->gender = 2;
			break;
		case BARBARIAN:
			npc_type->race = WOLF;
			npc_type->texture = 2;
			break;
		case IKSAR:
			npc_type->race = WOLF;
			npc_type->texture = 0;
			npc_type->gender = 1;
			npc_type->size *= 2.0f;
			npc_type->luclinface = 0;
			break;
		default:
			npc_type->race = WOLF;
			npc_type->texture = 0;
		}
	}

	// handle monster summoning pet appearance
	if(record.monsterflag) {

		uint32 monsterid = 0;

		// get a random npc id from the spawngroups assigned to this zone
		auto query = StringFormat("SELECT npcID "
									"FROM (spawnentry INNER JOIN spawn2 ON spawn2.spawngroupID = spawnentry.spawngroupID) "
									"INNER JOIN npc_types ON npc_types.id = spawnentry.npcID "
									"WHERE spawn2.zone = '%s' AND npc_types.bodytype NOT IN (11, 33, 66, 67) "
									"AND npc_types.race NOT IN (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 44, "
									"55, 67, 71, 72, 73, 77, 78, 81, 90, 92, 93, 94, 106, 112, 114, 127, 128, "
									"130, 139, 141, 183, 236, 237, 238, 239, 254, 266, 329, 330, 378, 379, "
									"380, 381, 382, 383, 404, 522) "
									"ORDER BY RAND() LIMIT 1", zone->GetShortName());
		auto results = database.QueryDatabase(query);
		if (!results.Success()) {
			return;
		}

		if (results.RowCount() != 0) {
			auto row = results.begin();
			monsterid = atoi(row[0]);
		}

		// since we don't have any monsters, just make it look like an earth pet for now
		if (monsterid == 0)
			monsterid = 567;

		// give the summoned pet the attributes of the monster we found
		const NPCType* monster = database.LoadNPCTypesData(monsterid);
		if(monster) {
			npc_type->race = monster->race;
			npc_type->size = monster->size;
			npc_type->texture = monster->texture;
			npc_type->gender = monster->gender;
			npc_type->luclinface = monster->luclinface;
			npc_type->helmtexture = monster->helmtexture;
			npc_type->herosforgemodel = monster->herosforgemodel;
		} else
			Log.Out(Logs::General, Logs::Error, "Error loading NPC data for monster summoning pet (NPC ID %d)", monsterid);

	}

	//this takes ownership of the npc_type data
	Pet *npc = new Pet(npc_type, this, (PetType)record.petcontrol, spell_id, record.petpower);

	// Now that we have an actual object to interact with, load
	// the base items for the pet. These are always loaded
	// so that a rank 1 suspend minion does not kill things
	// like the special back items some focused pets may receive.
	uint32 petinv[EmuConstants::EQUIPMENT_SIZE];
	memset(petinv, 0, sizeof(petinv));
	const Item_Struct *item = 0;

	if (database.GetBasePetItems(record.equipmentset, petinv)) {
		for (int i = 0; i<EmuConstants::EQUIPMENT_SIZE; i++)
			if (petinv[i]) {
				item = database.GetItem(petinv[i]);
				npc->AddLootDrop(item, &npc->itemlist, 0, 1, 127, true, true);
			}
	}

	npc->UpdateEquipmentLight();

	// finally, override size if one was provided
	if (in_size > 0.0f)
		npc->size = in_size;

	entity_list.AddNPC(npc, true, true);
	SetPetID(npc->GetID());
	// We need to handle PetType 5 (petHatelist), add the current target to the hatelist of the pet


	if (record.petcontrol == petTargetLock)
	{
		Mob* target = GetTarget();

		if (target){
			npc->AddToHateList(target, 1);
			npc->SetPetTargetLockID(target->GetID());
			npc->SetSpecialAbility(IMMUNE_AGGRO, 1);
		}
		else
			npc->Kill(); //On live casts spell 892 Unsummon (Kayen - Too limiting to use that for emu since pet can have more than 20k HP)
	}
}
Example #16
0
//      How to do a correlate-style CLASSIFY on some text.
//
int crm_expr_correlate_classify(CSL_CELL *csl, ARGPARSE_BLOCK *apb,
        VHT_CELL **vht,
        CSL_CELL *tdw,
        char *txtptr, int txtstart, int txtlen)
{
    //      classify the sparse spectrum of this input window
    //      as belonging to a particular type.
    //
    //       This code should look very familiar- it's cribbed from
    //       the code for LEARN
    //
    int i, j, k;
    char ptext[MAX_PATTERN]; //  the regex pattern
    int plen;
    //  the hash file names
    char htext[MAX_PATTERN + MAX_CLASSIFIERS * MAX_FILE_NAME_LEN];
    int htext_maxlen = MAX_PATTERN + MAX_CLASSIFIERS * MAX_FILE_NAME_LEN;
    int hlen;
    //  the match statistics variable
    char stext[MAX_PATTERN + MAX_CLASSIFIERS * (MAX_FILE_NAME_LEN + 100)];
    int stext_maxlen = MAX_PATTERN + MAX_CLASSIFIERS * (MAX_FILE_NAME_LEN + 100);
    int slen;
    char svrbl[MAX_PATTERN]; //  the match statistics text buffer
    int svlen;
    int fnameoffset;
    char fname[MAX_FILE_NAME_LEN];
    int eflags;
    int cflags;

    struct stat statbuf;    //  for statting the hash file
    //regex_t regcb;

    unsigned int fcounts[MAX_CLASSIFIERS]; // total counts for feature normalize

    double cpcorr[MAX_CLASSIFIERS];         // corpus correction factors
    int64_t linear_hits[MAX_CLASSIFIERS];   // actual hits per classifier
    int64_t square_hits[MAX_CLASSIFIERS];   // square of runlenths of match
    int64_t cube_hits[MAX_CLASSIFIERS];     // cube of runlength matches
    int64_t quad_hits[MAX_CLASSIFIERS];     // quad of runlength matches
    int incr_hits[MAX_CLASSIFIERS];         // 1+2+3... hits per classifier

    int64_t total_linear_hits; // actual total linear hits for all classifiers
    int64_t total_square_hits; // actual total square hits for all classifiers
    int64_t total_cube_hits;   // actual total cube hits for all classifiers
    int64_t total_quad_hits;   // actual total cube hits for all classifiers
    int64_t total_features;    // total number of characters in the system

    hitcount_t totalhits[MAX_CLASSIFIERS];
    double tprob;       //  total probability in the "success" domain.

    int textlen;  //  text length  - rougly corresponds to
    //  information content of the text to classify

    double ptc[MAX_CLASSIFIERS]; // current running probability of this class
    double renorm = 0.0;

    char *hashes[MAX_CLASSIFIERS];
    int hashlens[MAX_CLASSIFIERS];
    char *hashname[MAX_CLASSIFIERS];
    int succhash;
    int vbar_seen;     // did we see '|' in classify's args?
    int maxhash;
    int fnstart, fnlen;
    int fn_start_here;
    int textoffset;
    int bestseen;
    int thistotal;

    if (internal_trace)
        fprintf(stderr, "executing a CLASSIFY\n");

    //          we use the main line txtptr, txtstart, and txtlen now,
    //          so we don't need to extract anything from the b1start stuff.

    //           extract the hash file names
    hlen = crm_get_pgm_arg(htext, htext_maxlen, apb->p1start, apb->p1len);
    hlen = crm_nexpandvar(htext, hlen, htext_maxlen, vht, tdw);

    //           extract the "this is a word" regex
    //
    plen = crm_get_pgm_arg(ptext, MAX_PATTERN, apb->s1start, apb->s1len);
    plen = crm_nexpandvar(ptext, plen, MAX_PATTERN, vht, tdw);

    //            extract the optional "match statistics" variable
    //
    svlen = crm_get_pgm_arg(svrbl, MAX_PATTERN, apb->p2start, apb->p2len);
    svlen = crm_nexpandvar(svrbl, svlen, MAX_PATTERN, vht, tdw);
    {
        int vstart, vlen;
        if (crm_nextword(svrbl, svlen, 0, &vstart, &vlen))
        {
            crm_memmove(svrbl, &svrbl[vstart], vlen);
            svlen = vlen;
            svrbl[vlen] = 0;
        }
        else
        {
            svlen = 0;
            svrbl[0] = 0;
        }
    }

    //     status variable's text (used for output stats)
    //
    stext[0] = 0;
    slen = 0;

    //            set our flags, if needed.  The defaults are
    //            "case"
    cflags = REG_EXTENDED;
    eflags = 0;

    if (apb->sflags & CRM_NOCASE)
    {
        if (user_trace)
            fprintf(stderr, " setting NOCASE for tokenization\n");
        cflags += REG_ICASE;
        eflags = 1;
    }


    //       Now, the loop to open the files.
    bestseen = 0;
    thistotal = 0;

    //      initialize our arrays for N .css files
    for (i = 0; i < MAX_CLASSIFIERS; i++)
    {
        fcounts[i] = 0;       // check later to prevent a divide-by-zero
                              // error on empty .css file
        cpcorr[i] = 0.0;      // corpus correction factors
        linear_hits[i] = 0;   // linear hits
        square_hits[i] = 0;   // square of the runlength
        cube_hits[i] = 0;     // cube of the runlength
        quad_hits[i] = 0;     // quad of the runlength
        incr_hits[i] = 0;     // 1+2+3... hits hits
        totalhits[i] = 0;     // absolute hit counts
        ptc[i] = 0.5;         // priori probability
    }

    //

    vbar_seen = 0;
    maxhash = 0;
    succhash = 0;
    fnameoffset = 0;

    //    now, get the file names and mmap each file
    //     get the file name (grody and non-8-bit-safe, but doesn't matter
    //     because the result is used for open() and nothing else.
    //   GROT GROT GROT  this isn't NULL-clean on filenames.  But then
    //    again, stdio.h itself isn't NULL-clean on filenames.
    if (user_trace)
        fprintf(stderr, "Classify list: -%.*s-\n", hlen, htext);
    fn_start_here = 0;
    fnlen = 1;
    while (fnlen > 0 && ((maxhash < MAX_CLASSIFIERS - 1)))
    {
        if (crm_nextword(htext,
                         hlen, fn_start_here,
                         &fnstart, &fnlen)
           && fnlen > 0)
        {
            strncpy(fname, &htext[fnstart], fnlen);
            fname[fnlen] = 0;
            //      fprintf(stderr, "fname is '%s' len %d\n", fname, fnlen);
            fn_start_here = fnstart + fnlen + 1;
            if (user_trace)
            {
                fprintf(stderr, "Classifying with file -%s- succhash=%d, maxhash=%d\n",
                        fname, succhash, maxhash);
            }
            if (fname[0] == '|' && fname[1] == 0)
            {
                if (vbar_seen)
                {
                    nonfatalerror("Only one '|' allowed in a CLASSIFY.\n",
                                  "We'll ignore it for now.");
                }
                else
                {
                    succhash = maxhash;
                }
                vbar_seen++;
            }
            else
            {
                //  be sure the file exists
                //             stat the file to get it's length
                k = stat(fname, &statbuf);
                //             quick check- does the file even exist?
                if (k != 0)
                {
                    nonfatalerror("Nonexistent Classify table named: ",
                                  fname);
                }
                else
                {
                    // [i_a] check hashes[] range BEFORE adding another one!
                    if (maxhash >= MAX_CLASSIFIERS)
                    {
                        nonfatalerror("Too many classifier files.",
                                      "Some may have been disregarded");
                    }
                    else
                    {
                        //  file exists - do the mmap
                        //
                        hashlens[maxhash] = statbuf.st_size;
                        // [i_a] hashlens[maxhash] must be fixed for the header size!
                        hashes[maxhash] = crm_mmap_file(fname,
                                                        0,
                                                        hashlens[maxhash],
                                                        PROT_READ,
                                                        MAP_SHARED,
                                                        CRM_MADV_RANDOM,
                                                        &hashlens[maxhash]);
                        if (hashes[maxhash] == MAP_FAILED)
                        {
                            nonfatalerror("Couldn't memory-map the table file",
                                          fname);
                        }
                        else
                        {
                            //
                            //     Check to see if this file is the right version
                            //
                            //     FIXME : for now, there's no version number
                            //     associated with a .correllation file
                            // int fev;
                            // if (0)
                            //(hashes[maxhash][0].hash != 1 ||
                            //  hashes[maxhash][0].key  != 0)
                            //{
                            //  fev = fatalerror ("The .css file is the wrong version!  Filename is: ",
                            //                   fname);
                            //  return (fev);
                            //}

                            //
                            //     save the name for later...
                            //
                            hashname[maxhash] = (char *)calloc((fnlen + 10), sizeof(hashname[maxhash][0]));
                            if (!hashname[maxhash])
                            {
                                untrappableerror(
                                    "Couldn't alloc hashname[maxhash]\n", "We need that part later, so we're stuck.  Sorry.");
                            }
                            else
                            {
                                strncpy(hashname[maxhash], fname, fnlen);
                                hashname[maxhash][fnlen] = 0;
                            }
                            maxhash++;
                        }
                    }
                }
            }
        }
    }

    //
    //    If there is no '|', then all files are "success" files.
    if (succhash == 0)
        succhash = maxhash;

    //    a CLASSIFY with no arguments is always a "success".
    if (maxhash == 0)
        return 0;

    if (user_trace)
    {
        fprintf(stderr, "Running with %d files for success out of %d files\n",
                succhash, maxhash);
    }

    // sanity checks...  Uncomment for super-strict CLASSIFY.
    //
    //    do we have at least 1 valid .css files?
    if (maxhash == 0)
    {
        return nonfatalerror("Couldn't open at least 1 .css file for classify().", "");
    }

#if 0
    //    do we have at least 1 valid .css file at both sides of '|'?
    if (!vbar_seen || succhash <= 0 || (maxhash <= succhash))
    {
        return nonfatalerror("Couldn't open at least 1 .css file per SUCC | FAIL category "
                             "for classify().\n", "Hope you know what are you doing.");
    }
#endif

    //
    //   now all of the files are mmapped into memory,
    //   and we can do the correlations and add up matches.
    i = 0;
    j = 0;
    k = 0;
    thistotal = 0;

    //     put in the ptr/start/len values we got from the outside caller
    textoffset = txtstart;
    textlen = txtlen;

    //
    //    We keep track of the hits in these categories
    //  linear_hits[MAX_CLASSIFIERS];  // actual hits per classifier
    //  square_hits[MAX_CLASSIFIERS];  // square of runlenths of match
    //  incr_hits[MAX_CLASSIFIERS];  // 1+2+3... hits per classifier
    //

    //   Now we do the actual correllation.
    //   for each file...
    //    slide the incoming text (mdw->filetext[textofset])
    //     across the corpus text (hashes[] from 0 to hashlens[])
    //      and count the bytes that are the same, the runlengths,
    //       etc.

    for (k = 0; k < maxhash; k++)
    {
        int it;  // it is the start index into the tested text
        int ik;  // ik is the start index into the known corpus text
        int ilm; // ilm is the "local" matches (N in a row)

        //    for each possible displacement of the known  (ik) text...
        for (ik = 0;
             ik < hashlens[k];
             ik++)
        {
            int itmax;

            ilm = 0;
            itmax = textlen;
            if (ik + itmax > hashlens[k])
                itmax = hashlens[k] - ik;
            // for each position in the test (it) text...
            for (it = 0;
                 it < itmax;
                 it++)
            {
                //   do the characters in this position match?
                if (hashes[k][ik + it] == txtptr[textoffset + it])
                {
                    // yes they matched
                    linear_hits[k]++;
                    ilm++;
                    square_hits[k] = square_hits[k] + (ilm * ilm);
                    cube_hits[k] = cube_hits[k] + (ilm * ilm * ilm);
                    quad_hits[k] = quad_hits[k] + (ilm * ilm * ilm * ilm);
                }
                else
                {
                    //   nope, they didn't match.
                    //   So, we do the end-of-runlength stuff:
                    ilm = 0;
                }
                if (0)
                    fprintf(stderr, "ik: %d  it: %d  chars %c %c lin: %lld  sqr: %lld cube: %lld quad: %lld\n",
                            ik, it,
                            hashes[k][ik + it],
                            txtptr[textoffset + it],
                            (long long int)linear_hits[k],
                            (long long int)square_hits[k],
                            (long long int)cube_hits[k],
                            (long long int)quad_hits[k]);
            }
        }
    }


    //   Now we have the total hits for each text corpus.  We can then
    //  turn that into a vague probability measure, and then renormalize
    //  that to get probabilities.
    //
    //   But first, let's reflect on what we've got here.  We our test
    //   text, and we have a corpus which is "nominally correllated",
    //   and another corpus that is nominally uncorrellated.
    //
    //   The uncorrellated text will have an average match rate of 1/256'th
    //   in the linear domain (well, for random bytes; english text will match
    //   a lot more often, due to the fact that ASCII only uses the low 7
    //   bits, most text is written in lower case, Zipf's law, etc.
    //
    //   We can calculate a predicted total on a per-character basis for all
    //   of the corpi, then use that as an average expectation.

    //    Calculate total hits
    total_linear_hits = 0;
    total_square_hits = 0;
    total_cube_hits = 0;
    total_quad_hits = 0;
    total_features = 0;
    for (k = 0; k < maxhash; k++)
    {
        total_linear_hits += linear_hits[k];
        total_square_hits += square_hits[k];
        total_cube_hits += cube_hits[k];
        total_quad_hits += quad_hits[k];
        total_features += hashlens[k];
    }


    for (k = 0; k < maxhash; k++)
    {
        if (hashlens[k] > 0
           && total_features > 0)
        {
            //     Note that we don't normalize the probabilities yet- we do
            //     that down below.
            //
            //     .00397 is not a magic number - it's the random coincidence
            //     rate for 1 chance in 256, with run-length-squared boost.
            //     .00806 is the random coincidence rate for 7-bit characters.
            //
            //ptc[k] = ((0.0+square_hits[k] - (.00397 * hashlens[k] )));
            //      ptc[k] = ((0.0+square_hits[k] - (.00806 * hashlens[k] )))
            //        / hashlens[k];

            //      ptc[k] = (0.0+square_hits[k] ) / hashlens[k];
            //      ptc[k] = (0.0+ quad_hits[k] ) / hashlens[k];
            ptc[k] = (0.0 + quad_hits[k]) / linear_hits[k];

            if (ptc[k] < 0)
                ptc[k] = 10 * DBL_MIN;
        }
        else
        {
            ptc[k] = 0.5;
        }
    }


    //    ptc[k] = (sqrt (0.0 + square_hits[k])-linear_hits[k] ) / hashlens[k] ;
    //    ptc[k] =  (0.0 + square_hits[k] - linear_hits[k] ) ;
    //    ptc[k] =  ((0.0 + square_hits[k]) / hashlens[k]) ;
    //    ptc[k] = sqrt ((0.0 + square_hits[k]) / hashlens[k]) ;
    //    ptc[k] = ((0.0 + linear_hits[k]) / hashlens[k]) ;


    //   calculate renormalizer (the Bayesian formula's denomenator)
    renorm = 0.0;

    //   now calculate the per-ptc numerators
    for (k = 0; k < maxhash; k++)
        renorm = renorm + (ptc[k]);

    //   check for a zero normalizer
    if (renorm == 0)
        renorm = 1.0;

    //  and renormalize
    for (k = 0; k < maxhash; k++)
        ptc[k] = ptc[k] / renorm;

    //   if we have underflow (any probability == 0.0 ) then
    //   bump the probability back up to 10^-308, or
    //   whatever a small multiple of the minimum double
    //   precision value is on the current platform.
    //
    for (k = 0; k < maxhash; k++)
    {
        if (ptc[k] < 10 * DBL_MIN)
            ptc[k] = 10 * DBL_MIN;
    }

    if (internal_trace)
    {
        for (k = 0; k < maxhash; k++)
        {
            fprintf(stderr,
                    " file: %d  linear: %lld  square: %lld  RMS: %6.4e  ptc[%d] = %6.4e\n",
                    k, (long long int)linear_hits[k], (long long int)square_hits[k],
                    sqrt(0.0 + square_hits[k]), k, ptc[k]);
        }
    }

    //  end of repeat-the-regex loop


    //  cleanup time!
    //  remember to let go of the fd's and mmaps
    for (k = 0; k < maxhash; k++)
    {
        crm_munmap_file(hashes[k]);
    }

    if (user_trace)
    {
        for (k = 0; k < maxhash; k++)
            fprintf(stderr, "Probability of match for file %d: %f\n", k, ptc[k]);
    }
    //
    tprob = 0.0;
    for (k = 0; k < succhash; k++)
        tprob = tprob + ptc[k];
    //
    //      Do the calculations and format some output, which we may or may
    //      not use... but we need the calculated result anyway.
    //
    if (1 /* svlen > 0 */)
    {
        char buf[1024];
        double accumulator;
        double remainder;
        double overall_pR;
        int m;
        buf[0] = 0;
        accumulator = 10 * DBL_MIN;
        for (m = 0; m < succhash; m++)
        {
            accumulator += ptc[m];
        }
        remainder = 10 * DBL_MIN;
        for (m = succhash; m < maxhash; m++)
        {
            remainder += ptc[m];
        }
        overall_pR = log10(accumulator) - log10(remainder);

        //   note also that strcat _accumulates_ in stext.
        //  There would be a possible buffer overflow except that _we_ control
        //   what gets written here.  So it's no biggie.

        if (tprob > 0.5)
        {
            sprintf(buf, "CLASSIFY succeeds; (correlate) success probability: %6.4f  pR: %6.4f\n", tprob, overall_pR);
        }
        else
        {
            sprintf(buf, "CLASSIFY fails; (correlate) success probability: %6.4f  pR: %6.4f\n", tprob, overall_pR);
        }
        if (strlen(stext) + strlen(buf) <= stext_maxlen)
            strcat(stext, buf);

        //   find best single matching file
        //
        bestseen = 0;
        for (k = 0; k < maxhash; k++)
        {
            if (ptc[k] > ptc[bestseen])
            {
                bestseen = k;
            }
        }
        remainder = 10 * DBL_MIN;
        for (m = 0; m < maxhash; m++)
        {
            if (bestseen != m)
            {
                remainder += ptc[m];
            }
        }

        //   ... and format some output of best single matching file
        //
        snprintf(buf, WIDTHOF(buf), "Best match to file #%d (%s) "
                                    "prob: %6.4f  pR: %6.4f\n",
                 bestseen,
                 hashname[bestseen],
                 ptc[bestseen],
                 (log10(ptc[bestseen]) - log10(remainder)));
        buf[WIDTHOF(buf) - 1] = 0;
        if (strlen(stext) + strlen(buf) <= stext_maxlen)
            strcat(stext, buf);
        sprintf(buf, "Total features in input file: %d\n", hashlens[bestseen]);
        if (strlen(stext) + strlen(buf) <= stext_maxlen)
            strcat(stext, buf);

        //     Now do the per-file breakdowns:
        //
        for (k = 0; k < maxhash; k++)
        {
            int m;
            remainder = 10 * DBL_MIN;
            for (m = 0; m < maxhash; m++)
            {
                if (k != m)
                {
                    remainder += ptc[m];
                }
            }
            snprintf(buf, WIDTHOF(buf),
                     "#%d (%s):"
                     " features: %d, L1: %lld L2: %lld L3: %lld, L4: %lld prob: %3.2e, pR: %6.2f\n",
                     k,
                     hashname[k],
                     hashlens[k],
                     (long long int)linear_hits[k],
                     (long long int)square_hits[k],
                     (long long int)cube_hits[k],
                     (long long int)quad_hits[k],
                     ptc[k],
                     (log10(ptc[k]) - log10(remainder)));
            buf[WIDTHOF(buf) - 1] = 0;
            // strcat (stext, buf);
            if (strlen(stext) + strlen(buf) <= stext_maxlen)
                strcat(stext, buf);
        }
        // check here if we got enough room in stext to stuff everything
        // perhaps we'd better rise a nonfatalerror, instead of just
        // whining on stderr
        if (strcmp(&(stext[strlen(stext) - strlen(buf)]), buf) != 0)
        {
            nonfatalerror("WARNING: not enough room in the buffer to create "
                          "the statistics text.  Perhaps you could try bigger "
                          "values for MAX_CLASSIFIERS or MAX_FILE_NAME_LEN?",
                          " ");
        }
        if (svlen > 0)
        {
            crm_destructive_alter_nvariable(svrbl, svlen,                    stext, (int)strlen(stext), csl->calldepth);
        }
    }

    //
    //  Free the hashnames, to avoid a memory leak.
    //
    for (i = 0; i < maxhash; i++)
        free(hashname[i]);
    if (tprob <= 0.5)
    {
        if (user_trace)
            fprintf(stderr, "CLASSIFY was a FAIL, skipping forward.\n");
        //    and do what we do for a FAIL here
        CRM_ASSERT(csl->cstmt >= 0);
        CRM_ASSERT(csl->cstmt <= csl->nstmts);
#if defined(TOLERATE_FAIL_AND_OTHER_CASCADES)
        csl->next_stmt_due_to_fail = csl->mct[csl->cstmt]->fail_index;
#else
        csl->cstmt = csl->mct[csl->cstmt]->fail_index - 1;
#endif
        if (internal_trace)
        {
            fprintf(stderr, "CLASSIFY.CORRELATE is jumping to statement line: %d/%d\n", csl->mct[csl->cstmt]->fail_index, csl->nstmts);
        }
        CRM_ASSERT(csl->cstmt >= 0);
        CRM_ASSERT(csl->cstmt <= csl->nstmts);
        csl->aliusstk[csl->mct[csl->cstmt]->nest_level] = -1;
        return 0;
    }


    //
    //   all done... if we got here, we should just continue execution
    if (user_trace)
        fprintf(stderr, "CLASSIFY was a SUCCESS, continuing execution.\n");
// regcomp_failed:
    return 0;
}