Esempio n. 1
0
static int ois_expand_gsm7_to_bits(char *bits, const char *raw7, int len)
{
    int i, j, k;
    char ch;

    SAY(3, "ois_expand_gsm7_to_bits");

    len *= 7; /* number of bits in the gms 7-bit msg */

    for (j = i = 0; j < len; ++i) {
        ch = raw7[i];
        for (k = 0; k < 8; ++k) {
            bits[j++] = (char) (ch & 0x01);
            ch >>= 1;
        }
    }

    return j;
}
Esempio n. 2
0
static void ois_append_to_list(ois_listentry **head, Msg *msg)
{
    ois_listentry *item;
    ois_listentry *tail;

    SAY(2, "ois_append_to_list");

    item = gw_malloc(sizeof(ois_listentry));
    item->next = NULL;
    item->msg = msg;

    if (*head == NULL) {
        *head = item;
    } else { /* not so bright algorithm, but ok with relatively short lists */
        for (tail = *head; tail->next != NULL; tail = tail->next) ;
        tail->next = item;
    }
    return;
}
Esempio n. 3
0
static int ois_check_incoming(SMSCenter *smsc, long wait_usec)
{
    fd_set read_fd;
    struct timeval tv;
    int ret;

    SAY(8, "ois_check_incoming");

    tv.tv_sec = 0;
    tv.tv_usec = wait_usec;

    FD_ZERO(&read_fd);
    FD_SET(smsc->ois_listening_socket, &read_fd);
    ret = select(smsc->ois_listening_socket + 1, &read_fd, NULL, NULL, &tv);
    if (ret == -1) {
	if (errno == EINTR || errno == EAGAIN) {
	    return 0;
	} else {
	    error(errno, "ois_check_incoming: select failed");
	    smsc->ois_flags |= OIS_FLAG_ERROR;
	    return -1;
	}
    } else if (ret == 0) {
	return 0;
    }

    /* if we end up here, someone is trying to connect */

    if (smsc->socket != -1) {
	if ((smsc->ois_flags & OIS_FLAG_MULTIPLE_CALL) == 0) {
	    /* if you see lots of these, maybe we should accept */
	    /* multiple incoming connections at a time... */
	    debug("bb.sms.ois", 0, "letting an incoming call to wait until the old one disconnects");
	    smsc->ois_flags |= OIS_FLAG_MULTIPLE_CALL;
	}
	return 0;
    }

    smsc->ois_flags &= ~OIS_FLAG_MULTIPLE_CALL;
    return ois_open_receiver(smsc);
}
Esempio n. 4
0
void
sendUdpFlood (struct irc * bot, char * arg)
{
  char * next, * ip, * port_str, * qtd;
  int tam = 0, port_int = 0;
  next = gettoken (&ip, ' ', arg);
  next = gettoken (&port_str, ' ', next);
  next = gettoken (&qtd, ' ', next);
  chomp (ip); chomp (port_str); chomp (qtd);
  tam = atoi (qtd); port_int = atoi (port_str);
  SAY ("ip: %s :: port: %d :: qtd: %d \n", ip, port_int, tam);
  if (ip == NULL || port_int < 1 || port_int > 65535) {
    sendMsgChan (bot, "!udpflood ip porta tamanho\r\n");
    return; 
  } else
  if (tam < 1) 
    tam = 666;
  udpFlood (ip, port_int, tam);


}
Esempio n. 5
0
int ois_receive_msg(SMSCenter *smsc, Msg **msg)
{
    ois_listentry *item;

    ois_debug_level = smsc->ois_flags & OIS_FLAG_DEBUG;
    SAY(2, "ois_receive_msg");

    item = smsc->ois_received_mo;
    if (item == NULL) { /* no mo messages */
	if ((smsc->ois_flags & OIS_FLAG_ERROR) == 0) {
	    return 0;   /* should actually not happen */
	} else {
	    return -1;  /* error pending, reopen? */
	}
    } else {            /* we have a message waiting */
	smsc->ois_received_mo = item->next;
	*msg = item->msg;
	gw_free(item);
	return 1;       /* got the message */
    }
}
Esempio n. 6
0
static void ois_swap_buffering(SMSCenter *smsc)
{
    time_t alive;
    int socket;
    char *buffer;
    size_t bufsize;
    size_t buflen;

    SAY(8, "ois_swap_buffering");

    if (smsc->ois_bufsize == 0) {
	smsc->ois_buflen = 0;
	smsc->ois_bufsize = smsc->bufsize;
	smsc->ois_buffer = gw_malloc(smsc->ois_bufsize);
	memset(smsc->ois_buffer, 0, smsc->ois_bufsize);
    }

    alive = smsc->ois_alive;
    smsc->ois_alive = smsc->ois_alive2;
    smsc->ois_alive2 = alive;

    socket = smsc->socket;
    smsc->socket = smsc->ois_socket;
    smsc->ois_socket = socket;

    buffer = smsc->buffer;
    smsc->buffer = smsc->ois_buffer;
    smsc->ois_buffer = buffer;

    buflen = smsc->buflen;
    smsc->buflen = smsc->ois_buflen;
    smsc->ois_buflen = buflen;

    bufsize = smsc->bufsize;
    smsc->bufsize = smsc->ois_bufsize;
    smsc->ois_bufsize = bufsize;

    return;
}
Esempio n. 7
0
static int ois_deliver_sm_invoke(SMSCenter *smsc, const char *buffer)
{
    Msg *msg;
    int ret;

    SAY(2, "ois_deliver_sm_invoke");

    msg = msg_create(sms);

    ret = ois_decode_deliver_sm_invoke(msg, buffer);
    if (ret < 0) {
        goto error;
    }

    ois_append_to_list((ois_listentry **) &smsc->ois_received_mo, msg);

    return 0;

error:
    msg_destroy(msg);
    return -1;
}
Esempio n. 8
0
int ois_pending_smsmessage(SMSCenter *smsc)
{
    int ret;

    ois_debug_level = smsc->ois_flags & OIS_FLAG_DEBUG;
    SAY(8, "ois_pending_smsmessage");

    ret = ois_check_incoming(smsc, OIS_NOWAIT);
    if (ret == 0 && smsc->socket != -1) {
	ret = ois_check_input(smsc, OIS_NOWAIT);
    }
    if (ret == 0 && smsc->ois_socket != -1) {
	ois_swap_buffering(smsc);
	ret = ois_check_input(smsc, OIS_NOWAIT);
	ois_swap_buffering(smsc);
	if (smsc->ois_socket == -1 && smsc->ois_ack_debt != 0) {
	    warning(0, "ois_pending_smsmessage: missing %d ack(s)...",
		    smsc->ois_ack_debt);
	}
    }
    return ret;
}
Esempio n. 9
0
static int ois_check_deliver_sm_invoke(const char *str)
{
    int buflen;
    char buffer[BUFLEN+1];
    int count;

    SAY(3, "ois_check_deliver_sm_invoke");

    /* check the (initial) header and trailer */

    buflen = strlen(str) - 1;
    if (buflen < 7 || str[0] != 'M' || (str[1] & 0x50) != 0x50
	|| str[buflen] != EOL) {
	goto error;
    }

    count = str[1] & 0x0f;
    while (--count >= 0)
    {
	/* check the additional header */

	sprintf(buffer, "%c%c%c%.4s",
		EOL,
		'M',                      /* deliver sm invoke */
		(char)(0x60|count),       /* ia5 encoding, additional part */
		&str[2]);
	if (strstr(str, buffer) == NULL) {
	    goto error;
	}
    }

    return 0;
    
 error:
    return -1;
}
Esempio n. 10
0
int ois_reopen(SMSCenter *smsc)
{
    int ret;

    ois_debug_level = smsc->ois_flags & OIS_FLAG_DEBUG;
    SAY(2, "ois_reopen");

    ois_close(smsc);

    if (smsc->type == SMSC_TYPE_OIS) {
	ret = ois_open_listener(smsc);
	if (ret < 0) {
	    goto error;
	}
    } else {
	error(0, "ois_reopen: wrong smsc type");
	goto error;
    }
    return 0;

 error:
    error(0, "ois_reopen: could not open");
    return -1;
}
Esempio n. 11
0
static int ois_adjust_sm_text(Msg *msg, const char *raw)
{
    int msglen7, msglen8;
    char buffer[BUFLEN+1];

    SAY(3, "ois_adjust_sm_text");

    /* calculate lengths */

    msglen7 = raw[0] & 0xff;
    msglen8 = raw[1] & 0xff;

    /* copy text, note: flag contains temporarily the raw type description */

    switch ((msg->sms.coding - 1) & 0xff) { 
    case 0x00: /* gsm7 */
	ois_expand_gsm7(buffer, &raw[2], msglen7);
	ois_convert_to_iso88591(buffer, msglen7);
	if (msg->sms.mclass & 0x02) { /* XXX mclass temporarily */
	    msg->sms.msgdata = octstr_create("");
	    msg->sms.udhdata = octstr_create_from_data(buffer, msglen7);
	} else {
	    msg->sms.msgdata = octstr_create_from_data(buffer, msglen7);
	    msg->sms.udhdata = octstr_create("");
	}
	msg->sms.coding = DC_7BIT;
	break;
    case 0x0f: /* ia5 */
	memcpy(buffer, &raw[2], msglen8);
	ois_convert_to_iso88591(buffer, msglen8);
	if (msg->sms.mclass & 0x02) { /* XXX mclass temporarily */
	    msg->sms.msgdata = octstr_create("");
	    msg->sms.udhdata = octstr_create_from_data(buffer, msglen8);
	} else {
	    msg->sms.msgdata = octstr_create_from_data(buffer, msglen8);
	    msg->sms.udhdata = octstr_create("");
	}
	msg->sms.coding = DC_7BIT;
	break;
    default: /* 0xf4, 0xf5, 0xf6, 0xf7; 8bit to disp, mem, sim or term */ 
	if (msg->sms.mclass & 0x02) { /* XXX mclass temporarily */
	    msg->sms.msgdata = octstr_create("");
	    msg->sms.udhdata = octstr_create_from_data(&raw[2], msglen8);
	} else {
	    msg->sms.msgdata = octstr_create_from_data(&raw[2], msglen8);
	    msg->sms.udhdata = octstr_create("");
	}
	msg->sms.coding = DC_8BIT;
	break;
    }
    msg->sms.mclass = MC_UNDEF;

    if (octstr_len(msg->sms.udhdata)) {
	IOTRACE("decoded udh", octstr_get_cstr(msg->sms.udhdata),
		octstr_len(msg->sms.udhdata));
    } else {
	IOTRACE("decoded", octstr_get_cstr(msg->sms.msgdata),
		octstr_len(msg->sms.msgdata));
    }

    return 2 + msglen8;
}
Esempio n. 12
0
int main(int argc, char **argv) {
    // Check command-line options
    char *p;
    int a = 1;
    Fl::args(argc, argv, a);
    Fl::scheme(NULL);  // NULL causes libr. to look up style in .Xdefaults

    memset(ExprEntry_str, '\0', sizeof(ExprEntry_str));
    clear_content();

/*    
    printf("fround(0.0) is %1.2lf\n", fround(0.0));
    printf("fround(0.1) is %1.2lf\n", fround(0.1));
    printf("fround(0.49) is %1.2lf\n", fround(0.49));
    printf("fround(0.50) is %1.2lf\n", fround(0.50));
    printf("fround(0.51) is %1.2lf\n", fround(0.51));
    printf("fround(0.9) is %1.2lf\n", fround(0.9));
    printf("fround(1.0) is %1.2lf\n", fround(1.0));
    printf("fround(1.1) is %1.2lf\n", fround(1.1));
    printf("fround(-0.1) is %1.2lf\n", fround(-0.1));
    printf("fround(-0.4) is %1.2lf\n", fround(-0.4));
    printf("fround(-0.5) is %1.2lf\n", fround(-0.5));
    printf("fround(-0.51) is %1.2lf\n", fround(-0.51));
    printf("fround(-0.9) is %1.2lf\n", fround(-0.9));
    printf("fround(-1.0) is %1.2lf\n", fround(-1.0));
    printf("fround(-1.1) is %1.2lf\n", fround(-1.1));
    printf("fround(-1.4) is %1.2lf\n", fround(-1.4));
    printf("fround(-1.5) is %1.2lf\n", fround(-1.5));
    printf("fround(-1.6) is %1.2lf\n", fround(-1.6));
    printf("fround(-1.9) is %1.2lf\n", fround(-1.9));
    printf("\n");
    
    printf("123.34 has %d significant digits\n", sig_digits(123.45));
    printf("7 has %d significant digits\n", sig_digits(7));
    printf("654.00001 has %d significant digits\n", sig_digits(654.00001));
    printf("-123.34 has %d significant digits\n", sig_digits(-123.45));
    printf("-7 has %d significant digits\n", sig_digits(-7));
    printf("-654.00001 has %d significant digits\n", sig_digits(-654.00001));
    printf("1.234e10 has %d significant digits\n", sig_digits(1.234e10));
    printf("0.0001200560000 has %d significant digits\n", sig_digits(0.0001200560000));
    printf("-1.20056e-4 has %d significant digits\n", sig_digits(-1.20056e-4));

    //return 0;
*/    
    char num_str[8];
    int i;
    for(i = 0; i < MAXENTRY; i++) {
        sprintf(num_str, "%d\n", i);
        strcat(RowLabels_str, num_str);
    }

    //printf("argc is %d\n", argc); fflush(0);
    char cmdline_expr[MAXENTRYLEN] = "";
    char expr_prepped_str[MAXENTRYLEN] = "";
    while (a < argc) {
        p = argv[a];
        if (*p == '-' && *(p+1) == '-') {
            // OK, it's some kind of option
            char option = *(p+2);
            if (option == 't') {
                // Change terseness/verbosity threshold
                if (*(p+3)) {
                    SayThreshold = *(p+3) - '0';
                    SAY(1, "Terseness level is %d\n", SayThreshold); 
                }
                else if (a+1 < argc) {
                    a++;
                    p = argv[a];
                    SayThreshold = *p - '0';
                    SAY(1, "Terseness level is %d\n", SayThreshold); 
                }
            }
            else if (option == 'd') {
                // Change angle encoding to degrees 
                AngleUnitsAreDegrees = 1;
                SAY(1, "Angles expressed as degrees\n"); 
            }
            else if (option == 'r') {
                // Change angle encoding to radians 
                AngleUnitsAreDegrees = 0;
                SAY(1, "Angles expressed as radians\n"); 
            }
            else if (option == 'p') {
                // Switch to Reverse Polish Notation (RPN) entry syntax
                InputMode = RPN_INPUT;
                SAY(1, "Input syntanx mode is RPN (Reverse Polish Notation)\n"); fflush(0);
            }
            else if (option == 'v') {
                // Print name and version 
                update_main_win_title();
                printf("%s\n", Title_str); fflush(0);
            }
            else if (option == 'f') {
                // Pre-load a specific workspace content file 
                char filespec_str[MAXENTRYLEN] = "";
                if (*(p+3)) {
                    strcpy (CurrentFileSpec_str, (p+3));
                }
                else {
                    a++;
                    if (*argv[a]) {
                        strcpy (CurrentFileSpec_str, argv[a]);
                    }
                }
                if (!*CurrentFileSpec_str) {
                    fl_alert("File not specified!\n");
                }
            }
            a++;
        }
        else {
            // assume the remainder of command-line is math expression
            while (a < argc) {
                strncat(cmdline_expr, argv[a], 32);
                strcat(cmdline_expr, " ");
                a++;
            }
            SAY(1, "Commandline expression is '%s'\n", cmdline_expr);
            if (strlen(cmdline_expr)) {
                int rc = calculate_expr(cmdline_expr, ExprEntry_str[Result], Result);
                if (rc == CALC_SUCCESS) {
                    char result_str[64];
                    render_item(result_str, &ResultList[Result]);
                    printf("%s = %s\n", ExprEntry_str[Result], result_str);
                    return 0;
                }
                else {
                    if (rc == CALC_UNBALANCED) {
                        printf("Expression is unbalanced! Check parentheses carefully.\n");
                    }
                    else if (rc == CALC_ERROR) {
                        printf("Expression cannot be calculated!\n");
                    }
                    return 1;
                }
            }
        }
    }
    //fl_register_images();
    update_main_win_title();
    MainWin_p = new Fl_Window(560,352, Title_str);

    MainWin_p->begin();
    
    Fl_Scroll expr_win_scroll(6, 12, 546, 258);
    expr_win_scroll.begin();    
    Fl_Pack expr_win_group(6, 12, 546, 1024);
    expr_win_group.type(FL_HORIZONTAL);
    expr_win_group.begin();
  
    RowLabels_p = new Fl_Multiline_Output(6, 12,  30, 1024 );
    RowLabels_p->box(FL_FLAT_BOX);
    RowLabels_p->color(FL_BACKGROUND_COLOR);
    RowLabels_p->align(FL_ALIGN_RIGHT);
    RowLabels_p->value(RowLabels_str);
    
    WorkArea_p = new Fl_Multiline_Input(40, 10,  500, 1024 );
    WorkArea_p->box(FL_FLAT_BOX);
    WorkArea_p->label("");
    WorkArea_p->when(FL_WHEN_ENTER_KEY);
    WorkArea_p->callback(workarea_callback);
    WorkArea_p->take_focus();
    update_results_display();
    WorkArea_p->position(0,0);
    expr_win_group.end();
    expr_win_scroll.end();
    
    QuitBtn_p =  new Fl_Button(30, 280, 60, 30, "Quit");
    QuitBtn_p->callback(quit_callback);
    QuitBtn_p->shortcut(FL_Escape);
        
    OpenBtn_p =  new Fl_Button(120, 280, 60, 30, "Open...");
    OpenBtn_p->callback(open_callback);
    OpenBtn_p->shortcut(FL_CTRL + 'o');
        
    SaveBtn_p =  new Fl_Button(210, 280, 60, 30, "Save...");
    SaveBtn_p->callback(save_callback);
    SaveBtn_p->deactivate();
    SaveBtn_p->shortcut(FL_CTRL + 's');
        
    ClearBtn_p =  new Fl_Button(300, 280, 60, 30, "Clear");
    ClearBtn_p->callback(clear_callback);
    ClearBtn_p->shortcut(FL_CTRL + 'c');

    HintBtn_p =  new Fl_Button(420, 280, 30, 30, "!");
    HintBtn_p->callback(hint_callback);
    HintBtn_p->tooltip("Hints");
    HintBtn_p->shortcut(FL_CTRL + 'i');

    AboutBtn_p =  new Fl_Button(460, 280, 30, 30, "a");
    AboutBtn_p->callback(about_callback);
    AboutBtn_p->tooltip("About Flume");
    AboutBtn_p->shortcut(FL_CTRL + 'a');

    HelpBtn_p =  new Fl_Button(500, 280, 30, 30, "?");
    HelpBtn_p->callback(help_callback);
    HelpBtn_p->tooltip("Help (F1)");
    HelpBtn_p->shortcut(FL_F + 1);

    Fl_Box* pAngleLabel = new Fl_Box(20, 325, 40, 12, "Angles:");
    pAngleLabel->box(FL_FLAT_BOX);
    RadAngleBtn_p = new Fl_Round_Button(72, 324, 80, 16, "Radians");
    RadAngleBtn_p->value(AngleUnitsAreDegrees ? 0 : 1);
    RadAngleBtn_p->callback(radians_callback);

    DegAngleBtn_p = new Fl_Round_Button(152, 324, 80, 16, "Degrees");
    DegAngleBtn_p->value(AngleUnitsAreDegrees ? 1 : 0);
    DegAngleBtn_p->callback(degrees_callback);
    
    RpnModeChk_p = new Fl_Check_Button(280, 324, 96, 16, "RPN mode");
    RpnModeChk_p->value((InputMode == RPN_INPUT) ? 1 : 0);
    RpnModeChk_p->callback(rpn_callback);
    
    TrackSigChk_p = new Fl_Check_Button(392, 324, 140, 16, "Track significance");
    TrackSigChk_p->value(TrackSignificance);
    TrackSigChk_p->callback(track_sig_callback);
    
    MainWin_p->end();
    
    if (*CurrentFileSpec_str) {
        if (!load_content(CurrentFileSpec_str)) {
            fl_alert("File not loadable!\n");
        }
    }
    
    MainWin_p->show(argc, argv);
    Running = 1;
    while(Running && Fl::wait());
    return 0;
}
Esempio n. 13
0
static int ois_check_input(SMSCenter *smsc, long wait_usec)
{
    char buffer[BUFLEN+1];
    time_t now;
    int ret;

    SAY(8, "ois_check_input");

    ret = ois_read_into_buffer(smsc, wait_usec);
    if (ret < 0) {
	goto error;
    }

    ret = ois_extract_msg_from_buffer(buffer, smsc);
    if (ret > 0) {
	IOTRACE("received", buffer, ret);
	switch (buffer[0]) {
	case 's':
	    ret = ois_submit_sm_result(smsc, buffer);
	    if (ret > 0) {
		warning(0, "ois_check_input: submit sm result signals (%d)...", ret);
	    } else if (ret < 0) {
		error(0, "ois_check_input: invalid submit sm result");
		goto error;
	    }
	    --smsc->ois_ack_debt;
	    time(&smsc->ois_alive);
	    break;
	case 'M':
	    ret = ois_deliver_sm_invoke(smsc, buffer);
	    if (ret >= 0) {
		ret = ois_deliver_sm_result(smsc, ret, buffer);
		if (ret < 0) {
		    goto error;
		}
	    } else {
		error(0, "ois_check_input: invalid deliver sm invoke");
		goto error;
	    }
	    time(&smsc->ois_alive);
	    break;
	default:
	    warning(0, "ois_check_input: unexpected message [%s]...",
		    ois_debug_str(buffer, ret));
	    break;
	}
    } else {
	if (smsc->socket != -1) {
	    time(&now);
	    if ((now - smsc->ois_alive) > OIS_MESSAGE_WAITTIME) {
		debug("bb.sms.ois", 0, "closing an idle connection");
		SAY(4, "ois_check_input: ois_disconnect");
		ois_disconnect(smsc);
	    }
	}
    }

    if (ret < 0) {
	error(0, "ois_check_input: malformatted message [%s]",
	      ois_debug_str(buffer, -ret));
	goto error;
    }

    if (smsc->ois_received_mo != NULL ||
	(smsc->ois_flags & OIS_FLAG_ERROR) != 0) {
	SAY(2, "ois_check_input has something");
	return 1; /* at least one message in the queue or an error pending */
    } else {
	return 0; /* no messages this time */
    }

 error:
    smsc->ois_flags |= OIS_FLAG_ERROR;
    return 1;
}
Esempio n. 14
0
void handle_fork_program() {
  SAY("handling fork program\n");
  create_process_entry(R2);
}
Esempio n. 15
0
/* the main loop for the socket worker process */
void *socket_worker_thread(void *arg)
{
    socket_worker_t *self = (socket_worker_t *) arg;

    queue_t *main_queue = &self->queue;
    relay_socket_t *sck = NULL;

    queue_t private_queue;
    queue_t spill_queue;

    memset(&private_queue, 0, sizeof(queue_t));
    memset(&spill_queue, 0, sizeof(queue_t));

    const config_t *config = self->base.config;

    int join_err;

#define RATE_UPDATE_PERIOD 15
    time_t last_rate_update = 0;

    while (!RELAY_ATOMIC_READ(self->base.stopping)) {
        time_t now = time(NULL);

        if (!sck) {
            SAY("Opening forwarding socket");
            sck = open_output_socket_eventually(&self->base);
            if (sck == NULL || !(sck->type == SOCK_DGRAM || sck->type == SOCK_STREAM)) {
                FATAL_ERRNO("Failed to open forwarding socket");
                break;
            }
            connected_inc();
        }

        long since_rate_update = now - last_rate_update;
        if (since_rate_update >= RATE_UPDATE_PERIOD) {
            last_rate_update = now;
            update_rates(&self->rates[0], &self->totals, since_rate_update);
            update_rates(&self->rates[1], &self->totals, since_rate_update);
            update_rates(&self->rates[2], &self->totals, since_rate_update);
        }

        /* if we dont have anything in our local queue we need to hijack the main one */
        if (private_queue.head == NULL) {
            /* hijack the queue - copy the queue state into our private copy
             * and then reset the queue state to empty. So the formerly
             * shared queue is now private. We only do this if necessary.
             */
            if (!queue_hijack(main_queue, &private_queue, &GLOBAL.pool.lock)) {
                /* nothing to do, so sleep a while and redo the loop */
                worker_wait_millisec(config->polling_interval_millisec);
                continue;
            }
        }

        RELAY_ATOMIC_INCREMENT(self->counters.received_count, private_queue.count);

        /* ok, so we should have something in our queue to process */
        if (private_queue.head == NULL) {
            WARN("Empty private queue");
            break;
        }

        ssize_t wrote = 0;
        if (!process_queue(self, sck, &private_queue, &spill_queue, &wrote)) {
            if (!RELAY_ATOMIC_READ(self->base.stopping)) {
                WARN("Closing forwarding socket");
                close(sck->socket);
                sck = NULL;
                connected_dec();
            }
        }

        accumulate_and_clear_stats(&self->counters, &self->recents, &self->totals);
    }

    if (control_is(RELAY_STOPPING)) {
        SAY("Socket worker stopping, trying forwarding flush");
        stats_count_t old_sent = self->totals.sent_count;
        stats_count_t old_spilled = self->totals.spilled_count;
        stats_count_t old_dropped = self->totals.dropped_count;
        if (sck) {
            ssize_t wrote = 0;
            if (!process_queue(self, sck, &private_queue, &spill_queue, &wrote)) {
                WARN_ERRNO("Forwarding flush failed");
            }
            accumulate_and_clear_stats(&self->counters, &self->recents, &self->totals);
            SAY("Forwarding flush forwarded %zd bytes in %llu events, spilled %llu events, dropped %llu events ",
                wrote, (unsigned long long) (self->totals.sent_count - old_sent),
                (unsigned long long) (self->totals.spilled_count - old_spilled),
                (unsigned long long) (self->totals.dropped_count - old_dropped));
        } else {
            WARN("No forwarding socket to flush to");
        }
        SAY("Socket worker spilling any remaining events to disk");
        stats_count_t spilled = spill_all(self, &private_queue, &spill_queue);
        SAY("Socket worker spilled %llu events to disk", (unsigned long long) spilled);
    } else {
        accumulate_and_clear_stats(&self->counters, &self->recents, &self->totals);
    }

    SAY("worker[%s] in its lifetime received %lu sent %lu spilled %lu dropped %lu",
        (sck ? sck->to_string : self->base.arg),
        (unsigned long) RELAY_ATOMIC_READ(self->totals.received_count),
        (unsigned long) RELAY_ATOMIC_READ(self->totals.sent_count),
        (unsigned long) RELAY_ATOMIC_READ(self->totals.spilled_count),
        (unsigned long) RELAY_ATOMIC_READ(self->totals.dropped_count));

    if (sck) {
        close(sck->socket);
        connected_dec();
    }

    /* we are done so shut down our "pet" disk worker, and then exit with a message */
    RELAY_ATOMIC_OR(self->disk_writer->base.stopping, WORKER_STOPPING);

    join_err = pthread_join(self->disk_writer->base.tid, NULL);

    if (join_err)
        FATAL("shutting down disk_writer thread error: pthread error %d", join_err);

    free(self->disk_writer);

    return NULL;
}
Esempio n. 16
0
static int process_queue(socket_worker_t * self, relay_socket_t * sck, queue_t * private_queue, queue_t * spill_queue,
                         ssize_t * wrote)
{
    if (sck == NULL) {
        WARN("NULL forwarding socket");
        return 0;
    }

    blob_t *cur_blob;
    struct timeval now;
    struct timeval send_start_time;
    struct timeval send_end_time;
    stats_count_t spilled = 0;

    const config_t *config = self->base.config;
    const uint64_t spill_microsec = 1000 * config->spill_millisec;
    const uint64_t grace_microsec = 1000 * config->spill_grace_millisec;

    const struct sockaddr *dest_addr = (const struct sockaddr *) &sck->sa.in;
    socklen_t addr_len = sck->addrlen;

    int in_grace_period = 0;
    struct timeval grace_period_start;

    int failed = 0;

    *wrote = 0;

    get_time(&send_start_time);

    cork(sck, 1);

    while (private_queue->head != NULL) {
        get_time(&now);

        /* While not all the socket backends are present, for a configured maximum time,
         * do not spill/drop. This is a bit crude, better rules/heuristics welcome. */
        if (!connected_all()) {
            if (in_grace_period == 0) {
                in_grace_period = 1;
                get_time(&grace_period_start);
                SAY("Spill/drop grace period of %d millisec started", config->spill_grace_millisec);
            }
            if (elapsed_usec(&grace_period_start, &now) >= grace_microsec) {
                in_grace_period = 0;
                SAY("Spill/drop grace period of %d millisec expired", config->spill_grace_millisec);
            }
        } else {
            if (in_grace_period) {
                SAY("Spill/drop grace period of %d millisec canceled", config->spill_grace_millisec);
            }
            in_grace_period = 0;
        }

        if (in_grace_period == 0) {
            spilled += spill_by_age(self, config->spill_enabled, private_queue, spill_queue, spill_microsec, &now);
        }

        cur_blob = private_queue->head;
        if (!cur_blob)
            break;

        void *blob_data;
        ssize_t blob_size;

        if (sck->type == SOCK_DGRAM) {
            blob_size = BLOB_BUF_SIZE(cur_blob);
            blob_data = BLOB_BUF_addr(cur_blob);
        } else {                /* sck->type == SOCK_STREAM */
            blob_size = BLOB_DATA_MBR_SIZE(cur_blob);
            blob_data = BLOB_DATA_MBR_addr(cur_blob);
        }

        ssize_t blob_left = blob_size;
        ssize_t blob_sent = 0;
        int sendto_errno = 0;

        failed = 0;

        /* Keep sending while we have data left since a single sendto()
         * doesn't necessarily send all of it.  This may eventually fail
         * if sendto() returns -1. */
        while (!RELAY_ATOMIC_READ(self->base.stopping) && blob_left > 0) {
            const void *data = (const char *) blob_data + blob_sent;
            ssize_t sent;

            sendto_errno = 0;
            if (sck->type == SOCK_DGRAM) {
                sent = sendto(sck->socket, data, blob_left, MSG_NOSIGNAL, dest_addr, addr_len);
            } else {            /* sck->type == SOCK_STREAM */
                sent = sendto(sck->socket, data, blob_left, MSG_NOSIGNAL, NULL, 0);
            }
            sendto_errno = errno;

            if (0) {            /* For debugging. */
                peek_send(sck, data, blob_left, sent);
            }

            if (sent == -1) {
                WARN_ERRNO("sendto() tried sending %zd bytes to %s but sent none", blob_left, sck->to_string);
                RELAY_ATOMIC_INCREMENT(self->counters.error_count, 1);
                if (sendto_errno == EINTR) {
                    /* sendto() got interrupted by a signal.  Wait a while and retry. */
                    WARN("Interrupted, resuming");
                    worker_wait_millisec(config->sleep_after_disaster_millisec);
                    continue;
                }
                failed = 1;
                break;          /* stop sending from the hijacked queue */
            }

            blob_sent += sent;
            blob_left -= sent;
        }

        if (blob_sent == blob_size) {
            RELAY_ATOMIC_INCREMENT(self->counters.sent_count, 1);
        } else if (blob_sent < blob_size) {
            /* Despite the send-loop above, we failed to send all the bytes. */
            WARN("sendto() tried sending %zd bytes to %s but sent only %zd", blob_size, sck->to_string, blob_sent);
            RELAY_ATOMIC_INCREMENT(self->counters.partial_count, 1);
            failed = 1;
        }

        *wrote += blob_sent;

        if (failed) {
            /* We failed to send this packet.  Exit the loop, and
             * right after the loop close the socket, and get out,
             * letting the main loop to reconnect. */
            if ((sendto_errno == EAGAIN || sendto_errno == EWOULDBLOCK)) {
                /* Traffic jam.  Wait a while, but still get out. */
                WARN("Traffic jam");
                worker_wait_millisec(config->sleep_after_disaster_millisec);
            }
            break;
        } else {
            queue_shift_nolock(private_queue);
            blob_destroy(cur_blob);
        }
    }

    cork(sck, 0);

    get_time(&send_end_time);

    if (spilled) {
        if (config->spill_enabled) {
            WARN("Wrote %lu items which were over spill threshold", (unsigned long) spilled);
        } else {
            WARN("Spill disabled: DROPPED %lu items which were over spill threshold", (unsigned long) spilled);
        }
    }

    /* this assumes end_time >= start_time */
    uint64_t usec = elapsed_usec(&send_start_time, &send_end_time);
    RELAY_ATOMIC_INCREMENT(self->counters.send_elapsed_usec, usec);

    return failed == 0;
}
Esempio n. 17
0
/*----------------------------------------------------------------------------
ON COMPLETION OF AN AUDIO URB ITS DATA IS COPIED TO THE AUDIO BUFFERS
PROVIDED peasycap->audio_idle IS ZER0.  REGARDLESS OF THIS BEING TRUE,
IT IS RESUBMITTED PROVIDED peasycap->audio_isoc_streaming IS NOT ZERO.
-----------------------------------------------------------------------------*/
void
easysnd_complete(struct urb *purb)
{
struct easycap *peasycap;
struct data_buffer *paudio_buffer;
char errbuf[16];
__u8 *p1, *p2;
int i, j, more, much, leap, rc;
__s16 s16;

#if defined(UPSAMPLE)
int k;
__s16 oldaudio, newaudio, delta;
#endif /*UPSAMPLE*/

JOT(16,"\n");

if ( NULL == purb )
  {
  SAY("ERROR: purb is NULL\n");
  return;
  }
if ( NULL == ( peasycap = purb->context ))
  {
  SAY("ERROR: peasycap is NULL\n");
  return;
  }
much = 0;

if ( peasycap->audio_idle )
  {
  JOT(16,"%i=audio_idle  %i=audio_isoc_streaming\n", \
                       peasycap->audio_idle, peasycap->audio_isoc_streaming );
  if ( peasycap->audio_isoc_streaming )
    {
    if ( 0 != ( rc = usb_submit_urb( purb, GFP_ATOMIC ) ))
      {
      SAY("ERROR: while %i=audio_idle, usb_submit_urb() failed with rc:\n", \
                                                       peasycap->audio_idle );
      switch (rc)
        {
        case -ENOMEM:   { SAY("ENOMEM\n");    break; }
        case -ENODEV:   { SAY("ENODEV\n");    break; }
        case -ENXIO:    { SAY("ENXIO\n");     break; }
        case -EINVAL:   { SAY("EINVAL\n");    break; }
        case -EAGAIN:   { SAY("EAGAIN\n");    break; }
        case -EFBIG:    { SAY("EFBIG\n");     break; }
        case -EPIPE:    { SAY("EPIPE\n");     break; }
        case -EMSGSIZE: { SAY("EMSGSIZE\n");  break; }
        case -ENOSPC:   { SAY("ENOSPC\n");    break; }
        default:        { SAY("0x%08X\n",rc); break; }
        }
      }
    }
  return;
  }
/*---------------------------------------------------------------------------*/
if ( purb->status )
  {
  if (( -ESHUTDOWN == purb->status ) || \
         ( -ENOENT == purb->status ))
    {
    JOT(16,"urb status -ESHUTDOWN or -ENOENT\n");
    return;
    }
  SAY("ERROR: non-zero urb status:\n");
  switch ( purb->status )
    {
    case -EINPROGRESS:   { SAY("-EINPROGRESS\n"); break; }
    case -ENOSR:         { SAY("-ENOSR\n"); break; }
    case -EPIPE:         { SAY("-EPIPE\n"); break; }
    case -EOVERFLOW:     { SAY("-EOVERFLOW\n"); break; }
    case -EPROTO:        { SAY("-EPROTO\n"); break; }
    case -EILSEQ:        { SAY("-EILSEQ\n"); break; }
    case -ETIMEDOUT:     { SAY("-ETIMEDOUT\n"); break; }
    case -EMSGSIZE  :    { SAY("-EMSGSIZE\n"); break; }
    case -EOPNOTSUPP:    { SAY("-EOPNOTSUPP\n"); break; }
    case -EPFNOSUPPORT:  { SAY("-EPFNOSUPPORT\n"); break; }
    case -EAFNOSUPPORT:  { SAY("-EAFNOSUPPORT\n"); break; }
    case -EADDRINUSE:    { SAY("-EADDRINUSE\n"); break; }
    case -EADDRNOTAVAIL: { SAY("-EADDRNOTAVAIL\n"); break; }
    case -ENOBUFS:       { SAY("-ENOBUFS\n"); break; }
    case -EISCONN:       { SAY("-EISCONN\n"); break; }
    case -ENOTCONN:      { SAY("-ENOTCONN\n"); break; }
    case -ESHUTDOWN:     { SAY("-ESHUTDOWN\n"); break; }
    case -ENOENT:        { SAY("-ENOENT\n"); break; }
    case -ECONNRESET:    { SAY("-ECONNRESET\n"); break; }
    case -ENOSPC:        { SAY("-ENOSPC\n"); break; }
    default: { SAY("unknown error code 0x%08X\n", purb->status ); break; }
    }
  }
else
  {
#if defined(UPSAMPLE)
  oldaudio = peasycap->oldaudio;
#endif /*UPSAMPLE*/

  for ( i = 0;  i < purb->number_of_packets; i++ )
    {
    switch ( purb->iso_frame_desc[i].status )
      {
      case  0:             { strcpy(&errbuf[0],"OK"); break; }
      case -ENOENT:        { strcpy(&errbuf[0],"-ENOENT"); break; }
      case -EINPROGRESS:   { strcpy(&errbuf[0],"-EINPROGRESS"); break; }
      case -EPROTO:        { strcpy(&errbuf[0],"-EPROTO"); break; }
      case -EILSEQ:        { strcpy(&errbuf[0],"-EILSEQ"); break; }
      case -ETIME:         { strcpy(&errbuf[0],"-ETIME"); break; }
      case -ETIMEDOUT:     { strcpy(&errbuf[0],"-ETIMEDOUT"); break; }
      case -EPIPE:         { strcpy(&errbuf[0],"-EPIPE"); break; }
      case -ECOMM:         { strcpy(&errbuf[0],"-ECOMM"); break; }
      case -ENOSR:         { strcpy(&errbuf[0],"-ENOSR"); break; }
      case -EOVERFLOW:     { strcpy(&errbuf[0],"-EOVERFLOW"); break; }
      case -EREMOTEIO:     { strcpy(&errbuf[0],"-EREMOTEIO"); break; }
      case -ENODEV:        { strcpy(&errbuf[0],"-ENODEV"); break; }
      case -EXDEV:         { strcpy(&errbuf[0],"-EXDEV"); break; }
      case -EINVAL:        { strcpy(&errbuf[0],"-EINVAL"); break; }
      case -ECONNRESET:    { strcpy(&errbuf[0],"-ECONNRESET"); break; }
      case -ENOSPC:        { strcpy(&errbuf[0],"-ENOSPC"); break; }
      case -ESHUTDOWN:     { strcpy(&errbuf[0],"-ESHUTDOWN"); break; }
      default: { strcpy(&errbuf[0],"UNKNOWN" ); break; }
      }
    if (( ! purb->iso_frame_desc[i].status ) && 0 )
      {
      JOT(16,"frame[%2i]: %i=status{=%16s}  "  \
                        "%5i=actual  "  \
                        "%5i=length  "  \
                        "%3i=offset\n", \
                    i, purb->iso_frame_desc[i].status, &errbuf[0],
                       purb->iso_frame_desc[i].actual_length,
                       purb->iso_frame_desc[i].length,
                       purb->iso_frame_desc[i].offset);
      }
    if ( ! purb->iso_frame_desc[i].status )
      {
      more = purb->iso_frame_desc[i].actual_length;

#if defined(TESTTONE)
      if ( ! more ) more = purb->iso_frame_desc[i].length;
#endif

      if ( ! more ) peasycap->audio_mt++;
      else
        {
        if ( peasycap->audio_mt )
          {
          JOT(16,"%4i empty audio urb frames\n", peasycap->audio_mt );
          peasycap->audio_mt = 0;
          }

        p1 = (__u8 *)(purb->transfer_buffer + purb->iso_frame_desc[i].offset);

        leap = 0;
        p1 += leap;
        more -= leap;
/*-----------------------------------------------------------------------------
COPY more BYTES FROM ISOC BUFFER TO AUDIO BUFFER,
CONVERTING 8-BIT MONO TO 16-BIT SIGNED LITTLE-ENDIAN STEREO IF NECESSARY.
-----------------------------------------------------------------------------*/
        while ( more )
          {
          if ( 0 > more )
            {
            SAY("easysnd_complete: MISTAKE: more is negative\n");
            return;
            }
          if ( peasycap->audio_buffer_page_many <= peasycap->audio_fill )
            {
            SAY("ERROR: bad peasycap->audio_fill\n");
            return;
            }

          paudio_buffer = &peasycap->audio_buffer[ peasycap->audio_fill ];
          if ( PAGE_SIZE < ( paudio_buffer->pto - paudio_buffer->pgo ))
            {
            SAY("ERROR: bad paudio_buffer->pto\n");
            return;
            }
          if ( PAGE_SIZE == ( paudio_buffer->pto - paudio_buffer->pgo ))
            {

#if defined(TESTTONE)
            easysnd_testtone(peasycap, peasycap->audio_fill);
#endif /*TESTTONE*/

            paudio_buffer->pto = paudio_buffer->pgo;
            (peasycap->audio_fill)++;
            if (peasycap->audio_buffer_page_many <= peasycap->audio_fill) \
                                                    peasycap->audio_fill = 0;

            JOT(12,"bumped peasycap->audio_fill to %i\n", \
                                                      peasycap->audio_fill);

            paudio_buffer = &peasycap->audio_buffer[ peasycap->audio_fill ];
            paudio_buffer->pto = paudio_buffer->pgo;

            if ( ! ( peasycap->audio_fill % \
                                       peasycap->audio_pages_per_fragment ))
              {
              JOT(12,"wakeup call on wq_audio, " \
                             "%i=frag reading  %i=fragment fill\n", \
                             (peasycap->audio_read / \
                                        peasycap->audio_pages_per_fragment), \
                             (peasycap->audio_fill / \
                                        peasycap->audio_pages_per_fragment));
              wake_up_interruptible( &(peasycap->wq_audio) );
              }
            }

          much = PAGE_SIZE - (int)( paudio_buffer->pto - paudio_buffer->pgo );

          if ( false == peasycap->microphone )
            {
            if ( much > more ) much = more;

            memcpy( paudio_buffer->pto, p1, much);
            p1 += much;
            more -= much;
            }
          else
            {

#if defined(UPSAMPLE)
            if ( much % 16 ) JOT(8,"MISTAKE?  much is not divisible by 16\n");
            if ( much > ( 16 * more )) much = 16 * more ;
            p2 = (__u8 *)paudio_buffer->pto;

            for ( j = 0;  j < ( much / 16 );  j++ )
              {
              newaudio =  ((int) *p1 ) - 128;
              newaudio = 128 * newaudio;

              delta = (newaudio - oldaudio) / 4 ;
              s16 = oldaudio + delta;

              for ( k = 0;  k < 4;  k++ )
                {
                *p2       = ( 0x00FF & s16 );
                *(p2 + 1) = ( 0xFF00 & s16 ) >> 8;
                p2 += 2;
                *p2       = ( 0x00FF & s16 );
                *(p2 + 1) = ( 0xFF00 & s16 ) >> 8;
                p2 += 2;

                s16 += delta;
                }
              p1++;
              more--;
              oldaudio = s16;
              }

#else /* ! UPSAMPLE */
            if ( much > ( 2 * more )) much = 2 * more ;
            p2 = (__u8 *)paudio_buffer->pto;

            for ( j = 0;  j < ( much / 2 );  j++ )
              {
              s16 =  ((int) *p1 ) - 128;
              s16 = 128 * s16 ;
              *p2       = ( 0x00FF & s16 );
              *(p2 + 1) = ( 0xFF00 & s16 ) >> 8;

              p1++;  p2 += 2;
              more--;
              }
#endif /*UPSAMPLE*/

            }
          (paudio_buffer->pto) += much;
          }
        }
      }
    else
      {
      JOT(12,"discarding audio samples because " \
                                      "%i=purb->iso_frame_desc[i].status\n", \
                                          purb->iso_frame_desc[i].status );
      }
    }
Esempio n. 18
0
int
main(int argc, char ** argv, char ** env)
{
   enum cmssubcomreason rsn;
   int rv;
   char * str = "metest howdy there";
   struct eplist epl = {str, str + 7, str + strlen(str), 0};
   struct
   {
      char pl[3*8];
      char f[8];
   } p =
   {
      "METEST  " "HOWDY   " "THERE   ",
      FENCE,
   };
   char subc[3][8] = {"EXEC    ", "SUBMAP  ", FENCE};
   #define SAY(x) __say(x, strlen(x))
   FILE * f;

   printf("env %p [0] %p [1] %p extern %p\n", env, env[0], env[1], environ);
   for (; env && *env; env++)
   {
      printf("%s\n", * env);
   }
   printf("var %s\n", getenv("var"));


   rsn = cmssubcr("METEST", 0, &sub, "abc");
   printf("Register subcom rv %d\n", rsn);
   if (rsn) return rsn;
   SAY("Subcom chain:");
   rv = __svc204(0, subc[0], 0, 0);
   printf("End of subcom chain.  SUBMAP rv %d\n", rv);

   rv = __svc204(&epl, p.pl, 2 << 24, 0);
   printf("Subcom rv %d 0x%x\n", rv, rv);

   rv = system("jrexx gotest");
   printf("jrexx rv %d\n", rv);
   rv = cmssubdl("METEST");
   printf("Delete RV %d.  Subcom chain after delete:\n", rv);
   __svc204(0, subc[0], 0, 0);

/*********************************************************************/
/* Read a file that contains the record number as an integer.        */
/*********************************************************************/

   f = fopen(bfile, "rb");
   if (!f) printf("Cannot open %s:  %m\n", bfile);
   else
   {
      int i = 0, k;
      int ok = 1;

      printf("opened %s. eof %d\n", bfile, feof(f));
      for (i = 1; !feof(f); i++)
      {
         int rv;

         k = -1;
         rv = fread(&k, sizeof(k), 1, f);
         if (ferror(f))
         {
            printf("Could not read record %d\n", i);
            ok = 0;
            break;
         }

         if (feof(f)) break;

         if (1 != rv)
         {
            printf("Did not get 4 bytes for %d.  Got %d.\n", i, rv);
            ok = 0;
            break;
         }
         if (i != k)
         {
            printf("Expect %d; got %d\n", i, k);
            ok = 0;
            break;
         }
      }
      fclose(f);
      if (ok) printf("%d records read from filled\n", i);
   }
   return 0;
}
Esempio n. 19
0
void
easycap_testcard(struct easycap *peasycap, int field)
{
	int total;
	int y, u, v, r, g, b;
	unsigned char uyvy[4];
	int i1, line, k, m, n, more, much, barwidth, barheight;
	unsigned char bfbar[TESTCARD_BYTESPERLINE / 8], *p1, *p2;
	struct data_buffer *pfield_buffer;

	if (!peasycap) {
		SAY("ERROR: peasycap is NULL\n");
		return;
	}
	JOM(8, "%i=field\n", field);
	switch (peasycap->width) {
	case 720:
	case 360: {
		barwidth = (2 * 720) / 8;
		break;
	}
	case 704:
	case 352: {
		barwidth = (2 * 704) / 8;
		break;
	}
	case 640:
	case 320: {
		barwidth = (2 * 640) / 8;
		break;
	}
	default: {
		SAM("ERROR:  cannot set barwidth\n");
		return;
	}
	}
	if (TESTCARD_BYTESPERLINE < barwidth) {
		SAM("ERROR: barwidth is too large\n");
		return;
	}
	switch (peasycap->height) {
	case 576:
	case 288: {
		barheight = 576;
		break;
	}
	case 480:
	case 240: {
		barheight = 480;
		break;
	}
	default: {
		SAM("ERROR: cannot set barheight\n");
		return;
	}
	}
	total = 0;
	k = field;
	m = 0;
	n = 0;

	for (line = 0;  line < (barheight / 2);  line++) {
		for (i1 = 0;  i1 < 8;  i1++) {
			r = (i1 * 256)/8;
			g = (i1 * 256)/8;
			b = (i1 * 256)/8;

			y =  299*r/1000 + 587*g/1000 + 114*b/1000 ;
			u = -147*r/1000 - 289*g/1000 + 436*b/1000 ;
			u = u + 128;
			v =  615*r/1000 - 515*g/1000 - 100*b/1000 ;
			v = v + 128;

			uyvy[0] =  0xFF & u ;
			uyvy[1] =  0xFF & y ;
			uyvy[2] =  0xFF & v ;
			uyvy[3] =  0xFF & y ;

			p1 = &bfbar[0];
			while (p1 < &bfbar[barwidth]) {
				*p1++ = uyvy[0] ;
				*p1++ = uyvy[1] ;
				*p1++ = uyvy[2] ;
				*p1++ = uyvy[3] ;
				total += 4;
			}

			p1 = &bfbar[0];
			more = barwidth;

			while (more) {
				if ((FIELD_BUFFER_SIZE/PAGE_SIZE) <= m) {
					SAM("ERROR:  bad m reached\n");
					return;
				}
				if (PAGE_SIZE < n) {
					SAM("ERROR:  bad n reached\n");
					return;
				}

				if (0 > more) {
					SAM("ERROR:  internal fault\n");
					return;
				}

				much = PAGE_SIZE - n;
				if (much > more)
					much = more;
				pfield_buffer = &peasycap->field_buffer[k][m];
				p2 = pfield_buffer->pgo + n;
				memcpy(p2, p1, much);

				p1 += much;
				n += much;
				more -= much;
				if (PAGE_SIZE == n) {
					m++;
					n = 0;
				}
			}
		}
	}
	return;
}
Esempio n. 20
0
int main(int argc, char** argv) {
  s32 opt;
  u32 loop_cnt = 0, purge_age = 0, seed;
  u8 sig_loaded = 0, show_once = 0, no_statistics = 0,
     display_mode = 0, has_fake = 0;
  s32 oindex = 0;
  u8 *wordlist = NULL, *output_dir = NULL;
  u8 *sig_list_strg = NULL;
  u8 *gtimeout_str = NULL;
  u32 gtimeout = 0;

  struct termios term;
  struct timeval tv;
  u64 st_time, en_time;

  signal(SIGINT, ctrlc_handler);
  signal(SIGWINCH, resize_handler);
  signal(SIGPIPE, SIG_IGN);
  SSL_library_init();

/* Options, options, and options */

  static struct option long_options[] = {
    {"auth", required_argument, 0, 'A' },
    {"host", required_argument, 0, 'F' },
    {"cookie", required_argument, 0, 'C' },
    {"reject-cookies", required_argument, 0, 'N' },
    {"header", required_argument, 0, 'H' },
    {"user-agent", required_argument, 0, 'b' },
#ifdef PROXY_SUPPORT
    {"proxy", required_argument, 0, 'J' },
#endif /* PROXY_SUPPORT */
    {"max-depth", required_argument, 0, 'd' },
    {"max-child", required_argument, 0, 'c' },
    {"max-descendants", required_argument, 0, 'x' },
    {"max-requests", required_argument, 0, 'r' },
    {"max-rate", required_argument, 0, 'l'},
    {"probability", required_argument, 0, 'p' },
    {"seed", required_argument, 0, 'q' },
    {"include", required_argument, 0, 'I' },
    {"exclude", required_argument, 0, 'X' },
    {"skip-param", required_argument, 0, 'K' },
    {"skip-forms", no_argument, 0, 'O' },
    {"include-domain", required_argument, 0, 'D' },
    {"ignore-links", no_argument, 0, 'P' },
    {"no-ext-fuzzing", no_argument, 0, 'Y' },
    {"log-mixed-content", no_argument, 0, 'M' },
    {"skip-error-pages", no_argument, 0, 'Z' },
    {"log-external-urls", no_argument, 0, 'U' },
    {"log-cache-mismatches", no_argument, 0, 'E' },
    {"form-value", no_argument, 0, 'T' },
    {"rw-wordlist", required_argument, 0, 'W' },
    {"no-keyword-learning", no_argument, 0, 'L' },
    {"mode", required_argument, 0, 'J' },
    {"wordlist", required_argument, 0, 'S'},
    {"trust-domain", required_argument, 0, 'B' },
    {"max-connections", required_argument, 0, 'g' },
    {"max-host-connections", required_argument, 0, 'm' },
    {"max-fail", required_argument, 0, 'f' },
    {"request-timeout", required_argument, 0, 't' },
    {"network-timeout", required_argument, 0, 'w' },
    {"idle-timeout", required_argument, 0, 'i' },
    {"response-size", required_argument, 0, 's' },
    {"discard-binary", required_argument, 0, 'e' },
    {"output", required_argument, 0, 'o' },
    {"help", no_argument, 0, 'h' },
    {"quiet", no_argument, 0, 'u' },
    {"verbose", no_argument, 0, 'v' },
    {"scan-timeout", required_argument, 0, 'k'},
    {"signatures", required_argument, 0, 'z'},
    {"checks", no_argument, 0, 0},
    {"checks-toggle", required_argument, 0, 0},
    {"no-checks", no_argument, 0, 0},
    {"fast", no_argument, 0, 0},
    {"auth-form", required_argument, 0, 0},
    {"auth-form-target", required_argument, 0, 0},
    {"auth-user", required_argument, 0, 0},
    {"auth-user-field", required_argument, 0, 0},
    {"auth-pass", required_argument, 0, 0},
    {"auth-pass-field", required_argument, 0, 0},
    {"auth-verify-url", required_argument, 0, 0},
    {0, 0, 0, 0 }

  };
  /* Come up with a quasi-decent random seed. */

  gettimeofday(&tv, NULL);
  seed = tv.tv_usec ^ (tv.tv_sec << 16) ^ getpid();

  SAY("skipfish version " VERSION " by <*****@*****.**>\n");

  while ((opt = getopt_long(argc, argv,
          "+A:B:C:D:EF:G:H:I:J:K:LMNOPQR:S:T:UW:X:YZ"
          "b:c:d:ef:g:hi:k:l:m:o:p:q:r:s:t:uvw:x:z:",
          long_options, &oindex)) >= 0)

    switch (opt) {

      case 'A': {
          u8* x = (u8*)strchr(optarg, ':');
          if (!x) FATAL("Credentials must be in 'user:pass' form.");
          *(x++) = 0;
          auth_user = (u8*)optarg;
          auth_pass = x;
          auth_type = AUTH_BASIC;
          break;
        }

#ifdef PROXY_SUPPORT
      case 'J':  {
          u8* x = (u8*)strchr(optarg, ':');
          if (!x) FATAL("Proxy data must be in 'host:port' form.");
          *(x++) = 0;
          use_proxy = (u8*)optarg;
          use_proxy_port = atoi((char*)x);
          if (!use_proxy_port) FATAL("Incorrect proxy port number.");
          break;
        }
#endif /* PROXY_SUPPORT */

      case 'F': {
          u8* x = (u8*)strchr(optarg, '=');
          u32 fake_addr;
          if (!x) FATAL("Fake mappings must be in 'host=IP' form.");
          *x = 0;
          fake_addr = inet_addr((char*)x + 1);
          if (fake_addr == (u32)-1)
            FATAL("Could not parse IP address '%s'.", x + 1);
          fake_host((u8*)optarg, fake_addr);
          has_fake = 1;
          break;
        }

      case 'H': {
          u8* x = (u8*)strchr(optarg, '=');
          if (!x) FATAL("Extra headers must be in 'name=value' form.");
          *x = 0;
          if (!strcasecmp(optarg, "Cookie"))
            FATAL("Do not use -H to set cookies (try -C instead).");
          SET_HDR((u8*)optarg, x + 1, &global_http_par);
          break;
        }

      case 'C': {
          u8* x = (u8*)strchr(optarg, '=');
          if (!x) FATAL("Cookies must be in 'name=value' form.");
          if (strchr(optarg, ';'))
            FATAL("Split multiple cookies into separate -C options.");
          *x = 0;
          SET_CK((u8*)optarg, x + 1, &global_http_par);
          break;
        }

      case 'D':
        if (*optarg == '*') optarg++;
        APPEND_FILTER(allow_domains, num_allow_domains, optarg);
        break;

      case 'K':
        APPEND_FILTER(skip_params, num_skip_params, optarg);
        break;

      case 'B':
        if (*optarg == '*') optarg++;
        APPEND_FILTER(trust_domains, num_trust_domains, optarg);
        break;

      case 'I':
        if (*optarg == '*') optarg++;
        APPEND_FILTER(allow_urls, num_allow_urls, optarg);
        break;

      case 'X':
        if (*optarg == '*') optarg++;
        APPEND_FILTER(deny_urls, num_deny_urls, optarg);
        break;

      case 'T': {
          u8* x = (u8*)strchr(optarg, '=');
          if (!x) FATAL("Rules must be in 'name=value' form.");
          *x = 0;
          add_form_hint((u8*)optarg, x + 1);
          break;
        }

      case 'N':
        ignore_cookies = 1;
        break;

      case 'Y':
        no_fuzz_ext = 1;
        break;

      case 'q':
        if (sscanf(optarg, "0x%08x", &seed) != 1)
          FATAL("Invalid seed format.");
        srandom(seed);
        break;

      case 'Q':
        suppress_dupes = 1;
        break;

      case 'P':
        no_parse = 1;
        break;

      case 'M':
        warn_mixed = 1;
        break;

      case 'U':
        log_ext_urls = 1;
        break;

      case 'L':
        dont_add_words = 1;
        break;

      case 'E':
        pedantic_cache = 1;
        break;

      case 'O':
        no_forms = 1;
        break;

      case 'R':
        purge_age = atoi(optarg);
        if (purge_age < 3) FATAL("Purge age invalid or too low (min 3).");
        break;

      case 'd':
        max_depth = atoi(optarg);
        if (max_depth < 2) FATAL("Invalid value '%s'.", optarg);
        break;

      case 'c':
        max_children = atoi(optarg);
        if (!max_children) FATAL("Invalid value '%s'.", optarg);
        break;

      case 'x':
        max_descendants = atoi(optarg);
        if (!max_descendants) FATAL("Invalid value '%s'.", optarg);
        break;

      case 'p':
        crawl_prob = atoi(optarg);
        if (!crawl_prob) FATAL("Invalid value '%s'.", optarg);
        break;

      case 'W':
        if (wordlist)
          FATAL("Only one -W parameter permitted (use -S to load supplemental dictionaries).");

        if (!strcmp(optarg, "-")) wordlist = (u8*)"/dev/null";
        else wordlist = (u8*)optarg;

        break;

      case 'S':
        load_keywords((u8*)optarg, 1, 0);
        break;

      case 'z':
        load_signatures((u8*)optarg);
        sig_loaded = 1;
        break;

      case 'b':
        if (optarg[0] == 'i') browser_type = BROWSER_MSIE; else
        if (optarg[0] == 'f') browser_type = BROWSER_FFOX; else
        if (optarg[0] == 'p') browser_type = BROWSER_PHONE; else
          usage(argv[0]);
        break;

      case 'g':
        max_connections = atoi(optarg);
        if (!max_connections) FATAL("Invalid value '%s'.", optarg);
        break;

      case 'm':
        max_conn_host = atoi(optarg);
        if (!max_conn_host) FATAL("Invalid value '%s'.", optarg);
        break;

      case 'G':
        max_guesses = atoi(optarg);
        if (!max_guesses) FATAL("Invalid value '%s'.", optarg);
        break;

      case 'r':
        max_requests = atoi(optarg);
        if (!max_requests) FATAL("Invalid value '%s'.", optarg);
        break;

      case 'l':
        max_requests_sec = atof(optarg);
        if (!max_requests_sec) FATAL("Invalid value '%s'.", optarg);
        break;

      case 'f':
        max_fail = atoi(optarg);
        if (!max_fail) FATAL("Invalid value '%s'.", optarg);
        break;

      case 't':
        resp_tmout = atoi(optarg);
        if (!resp_tmout) FATAL("Invalid value '%s'.", optarg);
        break;

      case 'w':
        rw_tmout = atoi(optarg);
        if (!rw_tmout) FATAL("Invalid value '%s'.", optarg);
        break;

      case 'i':
        idle_tmout = atoi(optarg);
        if (!idle_tmout) FATAL("Invalid value '%s'.", optarg);
        break;

      case 's':
        size_limit = atoi(optarg);
        if (!size_limit) FATAL("Invalid value '%s'.", optarg);
        break;

      case 'o':
        if (output_dir) FATAL("Multiple -o options not allowed.");
        output_dir = (u8*)optarg;

        rmdir(optarg);

        if (mkdir(optarg, 0755))
          PFATAL("Unable to create '%s'.", output_dir);

        break;

      case 'u':
        no_statistics = 1;
        break;

      case 'v':
        verbosity++;
        break;


      case 'e':
        delete_bin = 1;
        break;

      case 'k':
        if (gtimeout_str) FATAL("Multiple -k options not allowed.");
        gtimeout_str = (u8*)optarg;
        break;

      case 'Z':
        no_500_dir = 1;
        break;

      case 0:
        if (!strcmp("checks", long_options[oindex].name ))
          display_injection_checks();
        if (!strcmp("checks-toggle", long_options[oindex].name ))
          toggle_injection_checks((u8*)optarg, 1, 1);
        if (!strcmp("no-checks", long_options[oindex].name ))
          no_checks = 1;
        if (!strcmp("signatures", long_options[oindex].name ))
          load_signatures((u8*)optarg);
        if(!strcmp("fast", long_options[oindex].name ))
          toggle_injection_checks((u8*)"2,4,5,13,14,15,16", 0, 0);
        if (!strcmp("auth-form", long_options[oindex].name ))
          auth_form = (u8*)optarg;
        if (!strcmp("auth-user", long_options[oindex].name ))
          auth_user = (u8*)optarg;
        if (!strcmp("auth-pass", long_options[oindex].name ))
          auth_pass = (u8*)optarg;
        if (!strcmp("auth-pass-field", long_options[oindex].name ))
          auth_pass_field = (u8*)optarg;
        if (!strcmp("auth-user-field", long_options[oindex].name ))
          auth_user_field = (u8*)optarg;
        if (!strcmp("auth-form-target", long_options[oindex].name ))
          auth_form_target = (u8*)optarg;
        if (!strcmp("auth-verify-url", long_options[oindex].name ))
          auth_verify_url = (u8*)optarg;

        break;

      default:
        usage(argv[0]);

  }

#ifdef PROXY_SUPPORT
  if (has_fake && use_proxy)
    FATAL("-F and -J should not be used together.");
#endif /* PROXY_SUPPORT */

  if (access(ASSETS_DIR "/index.html", R_OK))
    PFATAL("Unable to access '%s/index.html' - wrong directory?", ASSETS_DIR);

  srandom(seed);

  if (optind == argc)
    FATAL("Scan target not specified (try -h for help).");

  if (!output_dir)
    FATAL("Output directory not specified (try -h for help).");

  if(verbosity && !no_statistics && isatty(2))
    FATAL("Please use -v in combination with the -u flag or, "
          "run skipfish while redirecting stderr to a file. ");


  if (resp_tmout < rw_tmout)
    resp_tmout = rw_tmout;

  if (max_connections < max_conn_host)
    max_connections = max_conn_host;

  /* Parse the timeout string - format h:m:s */
  if (gtimeout_str) {
    int i = 0;
    int m[3] = { 1, 60, 3600 };

    u8* tok = (u8*)strtok((char*)gtimeout_str, ":");

    while(tok && i <= 2) {
      gtimeout += atoi((char*)tok) * m[i];
      tok = (u8*)strtok(NULL, ":");
      i++;
    }

    if(!gtimeout)
      FATAL("Wrong timeout format, please use h:m:s (hours, minutes, seconds)");
    DEBUG("* Scan timeout is set to %d seconds\n", gtimeout);
  }


  if (!wordlist) {
    wordlist = (u8*)"/dev/null";
    DEBUG("* No wordlist specified with -W: defaulting to /dev/null\n");
  }

  /* If no signature files have been specified via command-line: load
     the default file */
  if (!sig_loaded)
    load_signatures((u8*)SIG_FILE);

  load_keywords(wordlist, 0, purge_age);

  /* Load the signatures list for the matching */
  if (sig_list_strg) load_signatures(sig_list_strg);

  /* Try to authenticate when the auth_user and auth_pass fields are set. */
  if (auth_user && auth_pass) {
    authenticate();

    while (next_from_queue()) {
      usleep(1000);
    }

    switch (auth_state) {
      case ASTATE_DONE:
        DEBUGC(L1, "*- Authentication succeeded!\n");
        break;

      default:
        DEBUG("Auth state: %d\n", auth_state);
        FATAL("Authentication failed (use -uv for more info)\n");
        break;
    }
  }

  /* Schedule all URLs in the command line for scanning. */

  while (optind < argc) {
    struct http_request *req;

    /* Support @ notation for reading URL lists from files. */

    if (argv[optind][0] == '@') {
      read_urls((u8*)argv[optind++] + 1);
      continue;
    }

    req = ck_alloc(sizeof(struct http_request));

    if (parse_url((u8*)argv[optind], req, NULL))
      FATAL("Scan target '%s' is not a valid absolute URL.", argv[optind]);

    if (!url_allowed_host(req))
      APPEND_FILTER(allow_domains, num_allow_domains,
                    __DFL_ck_strdup(req->host));

    if (!url_allowed(req))
      FATAL("URL '%s' explicitly excluded by -I / -X rules.", argv[optind]);

    maybe_add_pivot(req, NULL, 2);
    destroy_request(req);

    optind++;
  }

  /* Char-by char stdin. */

  tcgetattr(0, &term);
  term.c_lflag &= ~ICANON;
  tcsetattr(0, TCSANOW, &term);
  fcntl(0, F_SETFL, O_NONBLOCK);

  gettimeofday(&tv, NULL);
  st_time = tv.tv_sec * 1000LL + tv.tv_usec / 1000;

#ifdef SHOW_SPLASH
  if (!no_statistics) splash_screen();
#endif /* SHOW_SPLASH */

  if (!no_statistics) SAY("\x1b[H\x1b[J");
  else SAY(cLGN "[*] " cBRI "Scan in progress, please stay tuned...\n");

  u64 refresh_time = 0;

  /* Enter the crawler loop */
  while ((next_from_queue() && !stop_soon) || (!show_once++)) {

    u8 keybuf[8];

    u64 end_time;
    u64 run_time;
    struct timeval tv_tmp;

    gettimeofday(&tv_tmp, NULL);
    end_time = tv_tmp.tv_sec * 1000LL + tv_tmp.tv_usec / 1000;

    run_time = end_time - st_time;
    if (gtimeout > 0 && run_time && run_time/1000 > gtimeout) {
      DEBUG("* Stopping scan due to timeout\n");
      stop_soon = 1;
    }

    req_sec = (req_count - queue_cur / 1.15) * 1000 / (run_time + 1);

    if (no_statistics || ((loop_cnt++ % 100) && !show_once && idle == 0))
      continue;

    if (end_time > refresh_time) {
      refresh_time = (end_time + 10);

      if (clear_screen) {
        SAY("\x1b[H\x1b[2J");
        clear_screen = 0;
      }

      SAY(cYEL "\x1b[H"
          "skipfish version " VERSION " by [email protected]\n\n"
           cBRI "  -" cPIN " %s " cBRI "-\n\n" cNOR,
           allow_domains[0]);


      if (!display_mode) {
        http_stats(st_time);
        SAY("\n");
        database_stats();
      } else {
        http_req_list();
      }

      SAY("        \r");
    }

    if (fread(keybuf, 1, sizeof(keybuf), stdin) > 0) {
      display_mode ^= 1;
      clear_screen = 1;
    }
  }

  gettimeofday(&tv, NULL);
  en_time = tv.tv_sec * 1000LL + tv.tv_usec / 1000;

  SAY("\n");

  if (stop_soon)
    SAY(cYEL "[!] " cBRI "Scan aborted by user, bailing out!" cNOR "\n");

  term.c_lflag |= ICANON;
  tcsetattr(0, TCSANOW, &term);
  fcntl(0, F_SETFL, O_SYNC);

  save_keywords((u8*)wordlist);

  write_report(output_dir, en_time - st_time, seed);

#ifdef LOG_STDERR
  SAY("\n== PIVOT DEBUG ==\n");
  dump_pivots(0, 0);
  SAY("\n== END OF DUMP ==\n\n");
#endif /* LOG_STDERR */

  SAY(cLGN "[+] " cBRI "This was a great day for science!" cRST "\n\n");

#ifdef DEBUG_ALLOCATOR
  if (!stop_soon) {
    destroy_database();
    destroy_signature_lists();
    destroy_http();
    destroy_signatures();
    __TRK_report();
  }
#endif /* DEBUG_ALLOCATOR */

  fflush(0);

  EVP_cleanup();
  CRYPTO_cleanup_all_ex_data();

  return 0;

}
Esempio n. 21
0
void handle_keyboard_read() {
  SAY("handling keyboad read\n");
  keyboard_read_req(current_pid);
  block_current_process();
  run_next_process();
}
Esempio n. 22
0
static int ois_open_sender(SMSCenter *smsc)
{
    int ret;
    char buffer[BUFLEN+1];
    time_t now;
    time_t beginning;
    
    SAY(2, "ois_open_sender");
    debug("bb.sms.ois", 0, "connecting to host %s port %d",
	  smsc->hostname, smsc->port);

    time(&beginning);
    smsc->socket = tcpip_connect_to_server(smsc->hostname, smsc->port,
		    NULL);
	/* XXX add interface_name if required */
    if (smsc->socket < 0) {
	return -1;
    } else {
	smsc->buflen = 0;
	time(&smsc->ois_alive);
	smsc->ois_ack_debt = 0;
    }

    SAY2(2, "ois_open_sender fd=%d", smsc->socket);
    if (smsc->ois_flags & OIS_FLAG_NOBANNER) {
	return 0;
    }

    buffer[0] = '\0';
    for (time(&now); (now - beginning) < OIS_OPEN_WAITTIME; time(&now)) {
	ret = ois_read_into_buffer(smsc, OIS_WAITTIME);
	if (ret < 0) {
	    goto error;
	}

	if (smsc->buflen == 0) {
	    /* assume that the router is in the quiet mode */
	    /* there will be no banners */
	    smsc->ois_flags |= OIS_FLAG_NOBANNER;
	    debug("bb.sms.ois", 0, "assuming that %s:%d is in the quiet mode",
		  smsc->hostname, smsc->port);
	    return 0;
	}
	ret = ois_extract_line_from_buffer(buffer, smsc);
	if (ret > 0) {
	    if (strncmp(buffer, "Trying", 6) == 0 &&
		strstr(buffer, "...Open\r\n") != NULL) {
		time(&smsc->ois_alive);
		return 0;
	    } else {
		break;
	    }
	}
    }

 error:
    SAY(4, "ois_open_sender: ois_disconnect in error");
    ois_disconnect(smsc);
    error(0, "ois_open_sender: failed to connect [%s%s]",
	  buffer, ois_debug_str(smsc->buffer, smsc->buflen));
    return -1;
}
Esempio n. 23
0
void workarea_callback(Fl_Widget* w)
{
    struct item eval_list[MAXITEMS];
    char disp_str[MAXENTRY*1024] = "\0";
    char expr_input_str[MAXENTRYLEN] = {0};
    char expr_prepped_str[MAXENTRYLEN] = {0};
    Result = 0;
    strcpy(disp_str, WorkArea_p->value());

    //printf("buf content is '%s'\n", disp_str); fflush(0);
    //printf("Result is %d\n", Result);
    const char * ep = disp_str;
    const char * p = ep;
    int disp_len = strlen(disp_str);
    
    while (Result < MAXENTRY && *ep && (ep - disp_str) < disp_len) {
        while (*p && *p != '\n' /*&& *p != '='*/) p++;
        int len = p - ep;
        if (len > (MAXENTRYLEN - 1)) {
            fl_alert("Entry is too long! (%d chars)", len);
            WorkArea_p->position(p - disp_str);
            return;
        }
        
        strncpy(expr_input_str, ep, len);
        expr_input_str[len] = '\0';
        SAY(0, "Expression entry %d is '%s'\n", Result, expr_input_str); fflush(0);
        
        int rc = calculate_expr(expr_input_str, ExprEntry_str[Result], Result);
        if (rc == CALC_SUCCESS) {
            Result++;
        }
        else {
            if (rc == CALC_UNBALANCED) {
                fl_alert("Expression on row %d is unbalanced!\nCheck parentheses carefully.", Result);
            }
            else if (rc == CALC_ERROR) {
                fl_alert("Expression on row %d cannot be calculated!\nCheck expression carefully.", Result);
            }
            else if (rc == CALC_EXPRLENGTH) {
                fl_alert("Expression on row %d too long!\nBreak into smaller parts.", Result);
            }
            WorkArea_p->position(p - disp_str);
            return;
        }
        //printf("*p is '%c', char # %d in buffer\n", *p, p - disp_str); fflush(0);
        while (*p && *p != '\n') p++;
        if (*p == '\n') p++;
        ep = p;
        //printf("(after) *p is '%c', char # %d in buffer\n", *p, p - disp_str); fflush(0);
        //printf("*ep is '%c', char # %d in buffer\n", *ep, ep - disp_str); fflush(0);
        Unsaved = 1;
        SaveBtn_p->activate();

    }
    if (p - disp_str < disp_len) {
        fl_alert("Row limit reached,\nremaining %d characters will be ignored!", 
                    disp_len - (p - disp_str));
    }
    
    update_results_display();
}
Esempio n. 24
0
static int usbctl_read_proc(char *page, char **start, off_t off,
			    int count, int *eof, void *data)
{
	const char * num_fmt   = "%25.25s: %8.8lX\n";
	const char * cnt_fmt   = "%25.25s: %lu\n";
	const char * yn_fmt    = "%25.25s: %s\n";
	const char * yes       = "YES";
	const char * no        = "NO";
	const char * mask      = "MASK";
	const char * enable    = "ENABLE";
	unsigned long v;
	unsigned long backup;
	char * p = page;
	int len;

	SAY( "S3C2410 USB Controller Core\n" );
	SAY( "USB state: %s (%s) %d\n",
		device_state_names[ sm_state_to_device_state[ sm_state ] ],
		state_names[ sm_state ],
		sm_state );

	SAYS( "ep0 bytes read", usbd_info.stats.ep0_bytes_read );
	SAYS( "ep0 bytes written", usbd_info.stats.ep0_bytes_written );
	SAYS( "ep0 FIFO read failures", usbd_info.stats.ep0_fifo_write_failures );
	SAYS( "ep0 FIFO write failures", usbd_info.stats.ep0_fifo_write_failures );
	 
	v = UD_FIFO0;
	SAY( "%25.25s: 0x%8.8lX - %ld\n", "EP_FIFO0", v, v );

	 
	SAY( "\n" );

	v = UD_FUNC;
	SAY( "%25.25s: 0x%8.8lX - %ld\n", "Address Register", v, v );

	backup = UD_INDEX;

	UD_INDEX = UD_INDEX_EP0;
	v = UD_MAXP;
	SAY( "%25.25s: %ld (%8.8lX)\n", "EP0 size(EP0)", v, v );
	 
	UD_INDEX = UD_INDEX_EP2;
	v = UD_MAXP;
	SAY( "%25.25s: %ld (%8.8lX)\n", "IN  max packet size(EP2)", v, v );
	UD_INDEX = UD_INDEX_EP1;
	v = UD_MAXP;
	SAY( "%25.25s: %ld (%8.8lX)\n", "OUT max packet size(EP1)", v, v );

	UD_INDEX = backup;


	v = UD_PWR;
	SAY( "\nUDC POWER Management Register\n" );
	SAYV( v );
	SAYC( "ISO Update(R)",    ( v & UD_PWR_ISOUP )     ? yes : no );
	SAYC( "USB Reset(R)",   ( v & UD_PWR_RESET ) ? yes : no );
	SAYC( "MCU Resume(RW)",  ( v & UD_PWR_RESUME  ) ? yes : no );
	SAYC( "Suspend Mode(R)",( v & UD_PWR_SUSPND ) ? yes : no );
	SAYC( "Suspend Mode enable bit(RW)",  ( v & UD_PWR_ENSUSPND ) ? yes : no );
		 
	 
	v = UD_INT;
	SAY( "\nUDC Interrupt Register\n" );
	SAYV( v );
	SAYC( "EP4 pending",        ( v & UD_INT_EP4 )     ? yes : no );
	SAYC( "EP3 pending",        ( v & UD_INT_EP3 )     ? yes : no );
	SAYC( "EP2 pending",        ( v & UD_INT_EP2 )     ? yes : no );
	SAYC( "EP1 pending",        ( v & UD_INT_EP1 )     ? yes : no );
	SAYC( "EP0 pending",        ( v & UD_INT_EP0 )     ? yes : no );

	v = UD_USBINT;
	SAY( "\nUSB Interrupt Register\n" );
	SAYV( v );
	SAYC( "Reset",        ( v & UD_USBINT_RESET )     ? yes : no );
	SAYC( "Resume",        ( v & UD_USBINT_RESUM )     ? yes : no );
	SAYC( "Suspend",        ( v & UD_USBINT_SUSPND )     ? yes : no );

	v = UD_INTE;
	SAY( "\nUDC Interrupt Enable Register\n" );
	SAYV( v );
	SAYC( "EP4",                !( v & UD_INTE_EP4 )    ? mask : enable );
	SAYC( "EP3",                !( v & UD_INTE_EP3 )    ? mask : enable );
	SAYC( "EP2",                !( v & UD_INTE_EP2 )    ? mask : enable );
	SAYC( "EP1",                !( v & UD_INTE_EP1 )    ? mask : enable );
	SAYC( "EP0",                !( v & UD_INTE_EP0 )    ? mask : enable );

	v = UD_USBINTE;
	SAY( "\nUSB Interrupt Enable Register\n" );
	SAYV( v );
	SAYC( "Reset",              !( v & UD_USBINTE_RESET )    ? mask : enable );
	SAYC( "Suspend",            !( v & UD_USBINTE_SUSPND )  ? mask : enable );

	len = ( p - page ) - off;
	if ( len < 0 )
	     len = 0;
	*eof = ( len <=count ) ? 1 : 0;
	*start = page + off;
	return len;
}
Esempio n. 25
0
int main(int argc,  char *argv[])
{
        int i=1;
	int align=0;
        size_t length=0;
        PMProtein *data,*mean,*evecs;
        float *evals=0;
        char *fnevecs=0, *fnmean=0, *fnvar=0, *fnevals=0;
	float S=1.0;
	
	data = pmCreateNew(PM_TYPE_MODEL);
        if(!data)
		FAIL("MALLOC: no memmory assigned")
	
	//loop options	
	while(i<argc){
                if(!strcmp(argv[i],"-h") || !strcmp(argv[i],"--help")){
                        fputs(help,stdout);
                        exit(0);
                }
                else if(!strcmp(argv[i],"--version")){
                        fputs(version,stdout);
                        exit(0);
                }
                else if(!strcmp(argv[i],"-s") || !strcmp(argv[i],"--structure")){
                        if(argv[i+1][0]!='-'){
                                i++;
				SAY("Reference: %s ...",argv[i]);
                        	if(!pmReadRefM((PMProteinModel*)data,argv[i])){
					 WARN("Can not read \"%s\" <- will be ignored",argv[i]);
				}
			}
                }
                else if(!strcmp(argv[i],"-m") || !strcmp(argv[i],"--mean")){
                        if(argv[i+1][0]!='-')
                                fnmean=argv[++i];
                }
                else if(!strcmp(argv[i],"-v") || !strcmp(argv[i],"--variance")){
                        if(argv[i+1][0]!='-')
                                fnvar=argv[++i];
                }
                else if(!strcmp(argv[i],"-S") || !strcmp(argv[i],"--evec-scale")){
                        if(argv[i+1][0]!='-')
                                S=atof(argv[++i]);
                }
                else if(!strcmp(argv[i],"-e") || !strcmp(argv[i],"--evecs")){
                        if(argv[i+1][0]!='-')
                                fnevecs=argv[++i];
                }
                else if(!strcmp(argv[i],"-V") || !strcmp(argv[i],"--evals")){
                        if(argv[i+1][0]!='-')
                                fnevals=argv[++i];
                }
                else if(!strcmp(argv[i],"-l") || !strcmp(argv[i],"--length")){
                        if(argv[i+1][0]!='-')
                                length=atoi(argv[++i]);
                }
                else if(!strcmp(argv[i],"-a") || !strcmp(argv[i],"--align")){
			align=1;
                }
		else if(argv[i][0]=='-'){
			WARN(" [Unkown argumant \"%s\"] <- will be ignored",argv[i]);
		}
                else if(argv[i][0]!='-'){
			SAY("try reading: %s ...",argv[i]);
                        if(!pmReadM((PMProteinModel*)data,argv[i])){
				 WARN("Can not read \"%s\" <- will be ignored",argv[i]);
                        }
                }
                i++;
	}


	pmPrintInfo(data);


	if(align){
		SAY("Alignment ...")
		pmCenter((PMProteinModel*)data,(PMProteinModel*)data);
		pmAlignTo((PMProteinModel*)data,(PMProteinModel*)data,(PMProteinModel*)data);
	}


	if(fnvar){
		SAY("Calculating mean and variance ...");
		mean = pmCreatefReff(data,2);
		if(!mean)
			FAIL("MALLOC: no memmory assigned")
		if(!pmMeanVar(mean,data))
			FAIL("CALC: calculation returned null pointer")
		if(fnmean) SAY("Writing %s ...",fnmean);
			pmWriteSM((PMProteinModel*)mean,fnmean,0);
		SAY("Writing %s ...",fnvar);
		pmWriteSM((PMProteinModel*)mean,fnvar,1);
	}
	else {
Esempio n. 26
0
static void usage(char* argv0) {
  SAY("Usage: %s [ options ... ] -W wordlist -o output_dir start_url [ start_url2 ... ]\n\n"

      "Authentication and access options:\n\n"

      "  -A user:pass      - use specified HTTP authentication credentials\n"
      "  -F host=IP        - pretend that 'host' resolves to 'IP'\n"
      "  -C name=val       - append a custom cookie to all requests\n"
      "  -H name=val       - append a custom HTTP header to all requests\n"
      "  -b (i|f|p)        - use headers consistent with MSIE / Firefox / iPhone\n"
#ifdef PROXY_SUPPORT
     "   -J proxy          - use a specified HTTP proxy server\n"
#endif /* PROXY_SUPPORT */
      "  -N                - do not accept any new cookies\n"
      "  --auth-form url   - form authentication URL\n"
      "  --auth-user user  - form authentication user\n"
      "  --auth-pass pass  - form authentication password\n"
      "  --auth-verify-url -  URL for in-session detection\n\n"

      "Crawl scope options:\n\n"

      "  -d max_depth     - maximum crawl tree depth (%u)\n"
      "  -c max_child     - maximum children to index per node (%u)\n"
      "  -x max_desc      - maximum descendants to index per branch (%u)\n"
      "  -r r_limit       - max total number of requests to send (%u)\n"
      "  -p crawl%%        - node and link crawl probability (100%%)\n"
      "  -q hex           - repeat probabilistic scan with given seed\n"
      "  -I string        - only follow URLs matching 'string'\n"
      "  -X string        - exclude URLs matching 'string'\n"
      "  -K string        - do not fuzz parameters named 'string'\n"
      "  -D domain        - crawl cross-site links to another domain\n"
      "  -B domain        - trust, but do not crawl, another domain\n"
      "  -Z               - do not descend into 5xx locations\n"
      "  -O               - do not submit any forms\n"
      "  -P               - do not parse HTML, etc, to find new links\n\n"

      "Reporting options:\n\n"

      "  -o dir          - write output to specified directory (required)\n"
      "  -M              - log warnings about mixed content / non-SSL passwords\n"
      "  -E              - log all HTTP/1.0 / HTTP/1.1 caching intent mismatches\n"
      "  -U              - log all external URLs and e-mails seen\n"
      "  -Q              - completely suppress duplicate nodes in reports\n"
      "  -u              - be quiet, disable realtime progress stats\n"
      "  -v              - enable runtime logging (to stderr)\n\n"

      "Dictionary management options:\n\n"

      "  -W wordlist     - use a specified read-write wordlist (required)\n"
      "  -S wordlist     - load a supplemental read-only wordlist\n"
      "  -L              - do not auto-learn new keywords for the site\n"
      "  -Y              - do not fuzz extensions in directory brute-force\n"
      "  -R age          - purge words hit more than 'age' scans ago\n"
      "  -T name=val     - add new form auto-fill rule\n"
      "  -G max_guess    - maximum number of keyword guesses to keep (%d)\n\n"
      "  -z sigfile      - load signatures from this file\n\n"

      "Performance settings:\n\n"

      "  -g max_conn     - max simultaneous TCP connections, global (%u)\n"
      "  -m host_conn    - max simultaneous connections, per target IP (%u)\n"
      "  -f max_fail     - max number of consecutive HTTP errors (%u)\n"
      "  -t req_tmout    - total request response timeout (%u s)\n"
      "  -w rw_tmout     - individual network I/O timeout (%u s)\n"
      "  -i idle_tmout   - timeout on idle HTTP connections (%u s)\n"
      "  -s s_limit      - response size limit (%u B)\n"
      "  -e              - do not keep binary responses for reporting\n\n"

      "Safety settings:\n\n"

      "  -l max_req      - max requests per second (%f)\n"
      "  -k duration     - stop scanning after the given duration h:m:s\n\n"

      "Send comments and complaints to <*****@*****.**>.\n", argv0,
      max_depth, max_children, max_descendants, max_requests,
      MAX_GUESSES, max_connections, max_conn_host,
      max_fail, resp_tmout, rw_tmout, idle_tmout, size_limit, max_requests_sec);

  exit(1);
}
Esempio n. 27
0
int main(int argc,  char *argv[])
{
        int i=1;
        size_t length=0;
        PMProtein *data,*mean,*evecs;
        float *evals=0;
        char *fnevecs=0, *fnmean=0, *fnvar=0, *fnevals=0;
	
	data = pmCreateNew(PM_TYPE_DENSITY);
        if(!data)
		FAIL("MALLOC: no memmory assigned")
	
	//loop options	
	while(i<argc){
                if(!strcmp(argv[i],"-h") || !strcmp(argv[i],"--help")){
                        fputs(help,stdout);
                        exit(0);
                }
                else if(!strcmp(argv[i],"--version")){
                        fputs(version,stdout);
                        exit(0);
                }
                else if(!strcmp(argv[i],"-m") || !strcmp(argv[i],"--mean")){
                        if(argv[i+1][0]!='-')
                                fnmean=argv[++i];
			SAY("mean: %s",fnmean);
                }
                else if(!strcmp(argv[i],"-v") || !strcmp(argv[i],"--variance")){
                        if(argv[i+1][0]!='-')
                                fnvar=argv[++i];
			SAY("variance: %s",fnvar);
                }
                else if(!strcmp(argv[i],"-e") || !strcmp(argv[i],"--evecs")){
                        if(argv[i+1][0]!='-')
                                fnevecs=argv[++i];
			SAY("eigenvectors: %s",fnevecs);
                }
                else if(!strcmp(argv[i],"-V") || !strcmp(argv[i],"--evals")){
                        if(argv[i+1][0]!='-')
                                fnevals=argv[++i];
                        SAY("eigenvalues: %s",fnevals);
                }
                else if(!strcmp(argv[i],"-l") || !strcmp(argv[i],"--length")){
                        if(argv[i+1][0]!='-')
                                length=atoi(argv[++i]);
			SAY("number of eigenvectors: %lu",length);		
                }
		else if(argv[i][0]=='-'){
			WARN("Unkown argumant will be ignored \"%s\"",argv[i]);
		}
                else if(argv[i][0]!='-'){
			SAY("try reading: %s ...",argv[i]);
                        if(!pmReadD((PMProteinDensity*)data,argv[i])){
				 WARN("Can not read \"%s\" - will be ignored",argv[i]);
                        }
                }
                i++;
	}
	if(fnvar){
		SAY("Calculating mean and variance ...");
		mean = pmCreatefReff(data,2);
		if(!mean)
			FAIL("MALLOC: no memmory assigned")
		if(!pmMeanVar(mean,data))
			FAIL("CALC: calculation returned null pointer")
		if(fnmean) SAY("Writing %s ...",fnmean);
			pmWriteSD((PMProteinDensity*)mean,fnmean,0);
		SAY("Writing %s ...",fnvar);
		pmWriteSD((PMProteinDensity*)mean,fnvar,1);
		SAY("done");
	}
	else {