Esempio n. 1
0
static int handle_response(const struct sr_dev_inst *sdi)
{
	struct dev_context *devc;
	struct acquisition_state *acq;
	int expect_len;

	devc = sdi->priv;
	acq  = devc->acquisition;

	switch (devc->state) {
	case STATE_STATUS_REQUEST:
		acq->status = acq->reg_sequence[0].val & 0x7F;
		acq->mem_addr_fill = acq->reg_sequence[1].val;
		acq->duration_now  = acq->reg_sequence[2].val;
		break;
	case STATE_LENGTH_REQUEST:
		acq->mem_addr_next = READ_START_ADDR;
		acq->mem_addr_stop = acq->reg_sequence[0].val + READ_START_ADDR - 1;
		break;
	case STATE_READ_REQUEST:
		expect_len = (acq->mem_addr_next - acq->mem_addr_done
				+ acq->in_index) * sizeof(acq->xfer_buf_in[0]);
		if (acq->xfer_in->actual_length != expect_len) {
			sr_err("Received size %d does not match expected size %d.",
			       acq->xfer_in->actual_length, expect_len);
			devc->transfer_error = TRUE;
			return SR_ERR;
		}
		if (acq->rle_enabled)
			read_response_rle(acq);
		else
			read_response(acq);
		break;
	default:
		sr_err("BUG: unhandled response state %d.", devc->state);
		return SR_ERR_BUG;
	}

	return SR_OK;
}
Esempio n. 2
0
int mailsmtp_data_message_quit(mailsmtp * session,
                               const char * message,
                               size_t size)
{
    int r;
    
    r = send_data(session, message, size);
    if (r == -1)
        return MAILSMTP_ERROR_STREAM;
    
    r = send_quit(session);
    
    r = read_response(session);
    
    mailstream_close(session->stream);
    session->stream = NULL;
    
    switch(r) {
        case 250:
            return MAILSMTP_NO_ERROR;
            
        case 552:
            return MAILSMTP_ERROR_EXCEED_STORAGE_ALLOCATION;
            
        case 554:
            return MAILSMTP_ERROR_TRANSACTION_FAILED;
            
        case 451:
            return MAILSMTP_ERROR_IN_PROCESSING;
            
        case 452:
            return MAILSMTP_ERROR_INSUFFICIENT_SYSTEM_STORAGE;
            
        case 0:
            return MAILSMTP_ERROR_STREAM;
            
        default:
            return MAILSMTP_ERROR_UNEXPECTED_CODE;
    }
}
Esempio n. 3
0
int mailsmtp_mail(mailsmtp * session, const char * from)
{
  int r;
  char command[SMTP_STRING_SIZE];

  snprintf(command, SMTP_STRING_SIZE, "MAIL FROM:<%s>\r\n", from);
  r = send_command(session, command);
  if (r == -1)
    return MAILSMTP_ERROR_STREAM;
  r = read_response(session);

  switch (r) {
  case 250:
    return MAILSMTP_NO_ERROR;

  case 552:
    return MAILSMTP_ERROR_EXCEED_STORAGE_ALLOCATION;

  case 451:
    return MAILSMTP_ERROR_IN_PROCESSING;

  case 452:
    return MAILSMTP_ERROR_INSUFFICIENT_SYSTEM_STORAGE;

  case 550:
    return MAILSMTP_ERROR_MAILBOX_UNAVAILABLE;

  case 553:
    return MAILSMTP_ERROR_MAILBOX_NAME_NOT_ALLOWED;

  case 503:
    return MAILSMTP_ERROR_BAD_SEQUENCE_OF_COMMAND;

  case 0:
    return MAILSMTP_ERROR_STREAM;

  default:
    return MAILSMTP_ERROR_UNEXPECTED_CODE;
  }
}
Esempio n. 4
0
int mailesmtp_starttls(mailsmtp * session) {
  int r;

  if (!(session->esmtp & MAILSMTP_ESMTP_STARTTLS))
    return MAILSMTP_ERROR_STARTTLS_NOT_SUPPORTED;

  r = send_command(session, "STARTTLS\r\n");
  if (r == -1)
    return MAILSMTP_ERROR_STREAM;
  r = read_response(session);

  switch (r) {
  case 220:
    return MAILSMTP_NO_ERROR;

  case 454:
    return MAILSMTP_ERROR_STARTTLS_TEMPORARY_FAILURE;

  default:
    return MAILSMTP_ERROR_UNEXPECTED_CODE;
  }
}
Esempio n. 5
0
File: main.c Progetto: naaf/Master
void *run_com(void *arg) {
	char response[512];
	char **tab = NULL;
	int size;

	memset(response, 0, 1024);

	fprintf(stderr, "thread com demarre :\n");

	/*--------------Blocquer les signaux------------------*/
	sigset_t mask;
	sigfillset(&mask);
	pthread_sigmask(SIG_SETMASK, &mask, NULL);

	pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);

	while (TRUE) {
		read_response(sc, response);
		fprintf(stderr, "com: recu reponse len %zu : %s\n", strlen(response),
				response);

		if (0 == strlen(response)) {
			fprintf(stderr, "ERROR : Connection Socket");
			erreur("ERROR : Connection Socket", TRUE);
			break;
		}

		tab = string_to_arraystring(response, &size, '/');

		traitement(tab, size);

		/*free resources*/
		free_table(tab, size);
		memset(response, 0, sizeof(response));
	}
	pthread_cancel(thread_chat); //TODO
	return NULL;
}
Esempio n. 6
0
int main()
{
    struct sockaddr_in dest;

    int skt = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    int flags = fcntl(skt, F_GETFL, 0);
    fcntl(skt, F_SETFL, flags | O_NONBLOCK);

    dest.sin_family = AF_INET;
    dest.sin_port = htons(53);
    dest.sin_addr.s_addr = inet_addr("8.8.8.8");

    send_dns_query(skt, (struct sockaddr*)&dest, "pubsub.pubnub.com");

    fd_set read_set, write_set;
    int rslt;
    struct timeval timev = { 0, 300000 };
    
    FD_ZERO(&read_set);
    FD_SET(skt, &read_set);
    rslt = select(skt + 1, &read_set, NULL, NULL, &timev);
    if (-1 == rslt) {
        puts("select() Error!\n");
        return -1;
    }
    else if (rslt > 0) {
        struct sockaddr_in resolved_addr;
        printf("skt=%d, rslt=%d, timev.tv_sec=%ld, timev.tv_usec=%ld\n", skt, rslt, timev.tv_sec, timev.tv_usec);
        read_response(skt, (struct sockaddr*)&dest, "pubsub.pubnub.com", &resolved_addr);
    }
    else {
        puts("no select() event");
    }



    return 0;
}
Esempio n. 7
0
int mailsmtp_connect(mailsmtp * session, mailstream * s)
{
  int code;

  session->stream = s;

  code = read_response(session);

  switch (code) {
  case 220:
    return MAILSMTP_NO_ERROR;

  case 554:
    session->stream = NULL;
    mailstream_close(s);
    return MAILSMTP_ERROR_SERVICE_NOT_AVAILABLE;

  default:
    session->stream = NULL;
    mailstream_close(s);
    return MAILSMTP_ERROR_UNEXPECTED_CODE;
  }
}
Esempio n. 8
0
int
main(int argc, char **argv)
{
	char *errmsg;
	mdata_get_t mdg;

	if (argc < 2) {
		errx(MDEC_USAGE_ERROR, "Usage: %s <keyname>", argv[0]);
	}

	bzero(&mdg, sizeof (mdg));
	mdg.mdg_keyname = strdup(argv[1]);
	mdg.mdg_data = dynstr_new();

	if (open_metadata_stream(&mdg.mdg_fp, &errmsg) == -1) {
		errx(MDEC_TRY_AGAIN, "%s", errmsg);
	}

	write_get(&mdg);
	read_response(&mdg);
	print_response(&mdg);

	(void) fclose(mdg.mdg_fp);
	mdg.mdg_fp = NULL;
	free(mdg.mdg_keyname);

	if (mdg.mdg_state == MDGS_DONE) {
		if (mdg.mdg_response == MDGR_SUCCESS)
			return (MDEC_SUCCESS);
		else if (mdg.mdg_response == MDGR_NOTFOUND)
			return (MDEC_NOTFOUND);
		else
			return (MDEC_ERROR);
	} else {
		return (MDEC_TRY_AGAIN);
	}
}
Esempio n. 9
0
static void
add_recipient( char* recipient, int len )
    {
    char buf[1000], *ptr;
    int status;

    /* Skip leading whitespace. */
    while ( len > 0 && ( *recipient == ' ' || *recipient == '\t' ) )
	{
	++recipient;
	--len;
	}

    /* Strip off any angle brackets. */
	for(ptr = recipient; ptr < recipient+len; ptr++) {
		if ( *ptr == '<' )
		{
			len -= ptr-recipient+1;
			recipient = ptr+1;
		}
	}
    while ( len > 0 && recipient[len-1] == '>' )
	--len;

    (void) snprintf( buf, sizeof(buf), "RCPT TO:<%.*s>", len, recipient );
    send_command( buf );
    status = read_response();
    if ( status != 250  && status != 251 )
	{
	(void) fprintf(
	    stderr,  "%s: unexpected response %d to RCPT TO command\n",
	    argv0, status );
	exit( 1 );
	}
    got_a_recipient = 1;
    }
Esempio n. 10
0
OCSP_RESPONSE *modssl_dispatch_ocsp_request(const apr_uri_t *uri,
                                            apr_interval_time_t timeout,
                                            OCSP_REQUEST *request,
                                            conn_rec *c, apr_pool_t *p)
{
    OCSP_RESPONSE *response = NULL;
    apr_socket_t *sd;
    BIO *bio;
    const apr_uri_t *proxy_uri;

    proxy_uri = (mySrvConfigFromConn(c))->server->proxy_uri;
    bio = serialize_request(request, uri, proxy_uri);
    if (bio == NULL) {
        ap_log_cerror(APLOG_MARK, APLOG_ERR, 0, c, APLOGNO(01989)
                      "could not serialize OCSP request");
        ssl_log_ssl_error(SSLLOG_MARK, APLOG_ERR, mySrvFromConn(c));
        return NULL;
    }

    sd = send_request(bio, uri, timeout, c, p, proxy_uri);
    if (sd == NULL) {
        /* Errors already logged. */
        BIO_free(bio);
        return NULL;
    }

    /* Clear the BIO contents, ready for the response. */
    (void)BIO_reset(bio);

    response = read_response(sd, bio, c, p);

    apr_socket_close(sd);
    BIO_free(bio);

    return response;
}
Esempio n. 11
0
net_socket* http_connection::connect(const char* c_url, int port)
{
	char* url = strdup(c_url);

	// get host name from url
	// find the first '/'
	int i, n;
	for (i = 0, n = (int) strlen(url); url[i] != '/' && i < n; i++);
	if (i == n)
	{
		// '/' is not found
		fprintf(stderr, "invalid url '%s'\n", url);
		free(url);
		return NULL;
	}

	tu_string uri = url + i;
	url[i] = 0;
	tu_string host = url;
	free(url);
	url = NULL;

	if (net_init() == false)
	{
		return NULL;
	}

	m_iface = new net_interface_tcp();

	// Open a socket to receive connections on.
	m_ns = m_iface->connect(host.c_str(), port);

	if (m_ns == NULL)
	{
		fprintf(stderr, "Couldn't open net interface\n");
		delete m_iface;
		m_iface = NULL;
		return NULL;
	}

	// connect to HTTP server
	if (get_proxy_port() > 0)
	{
		char buf[512];
		snprintf(buf, 512, "CONNECT %s:%d HTTP/1.0\r\n", host.c_str(), port);
		m_ns->write_string(buf, HTTP_TIMEOUT);
		m_ns->write_string("User-Agent:gameswf\r\n", HTTP_TIMEOUT);
		m_ns->write_string("Connection:Keep-Alive\r\n", HTTP_TIMEOUT);
		m_ns->write_string("\r\n", HTTP_TIMEOUT);
		if (read_response() == false)
		{
			fprintf(stderr, "Couldn't connect to '%s' through proxy '%s'\n", 
				host.c_str(), get_proxy());
			delete m_ns;
			m_ns = NULL;
			return NULL;
		}
	}

	// We use HTTP/1.0 because we do not wont get chunked encoding data
	m_ns->write_string(tu_string("GET ") + uri + tu_string(" HTTP/1.0\r\n"), HTTP_TIMEOUT);
	m_ns->write_string(tu_string("Host:") + host + tu_string("\r\n"), HTTP_TIMEOUT);
	//	m_ns->write_string("Accept:*\r\n", HTTP_TIMEOUT);
	//	m_ns->write_string("Accept-Language: en\r\n", HTTP_TIMEOUT);
	//	m_ns->write_string("Accept-Encoding: gzip, deflate, chunked\r\n", HTTP_TIMEOUT);
	//	m_ns->write_string("Accept-Encoding: *\r\n", HTTP_TIMEOUT);
	//	m_ns->write_string("Proxy-Authenticate:prg\r\n", HTTP_TIMEOUT);
	//	m_ns->write_string("Proxy-Authorization:123\r\n", HTTP_TIMEOUT);
	m_ns->write_string("User-Agent:gameswf\r\n", HTTP_TIMEOUT);
	m_ns->write_string("Connection:Close\r\n", HTTP_TIMEOUT);

	m_ns->write_string("\r\n", HTTP_TIMEOUT);

	if (read_response() == false)
	{
		fprintf(stderr, "Couldn't find resource '%s', host '%s'\n", 
			uri.c_str(), host.c_str());
		delete m_ns;
		m_ns = NULL;
		return NULL;
	}

	return m_ns;
}
Esempio n. 12
0
static CvsServerCtx * open_ctx_pserver(CvsServerCtx * ctx, const char * p_root)
{
    char root[PATH_MAX];
    char full_root[PATH_MAX];
    char * p = root, *tok, *tok2;
    char user[BUFSIZ];
    char server[BUFSIZ];
    char pass[BUFSIZ];
    char port[8];

    strcpy_a(root, p_root, PATH_MAX);

    tok = strsep(&p, ":");
    if (strlen(tok) == 0 || !p)
    {
	debug(DEBUG_APPERROR, "parse error on third token");
	goto out_free_err;
    }

    tok2 = strsep(&tok, "@");
    if (!strlen(tok2) || (!tok || !strlen(tok)))
    {
	debug(DEBUG_APPERROR, "parse error on user@server in pserver");
	goto out_free_err;
    }

    strcpy_a(user, tok2, BUFSIZ);
    strcpy_a(server, tok, BUFSIZ);
    
    if (*p != '/')
    {
	tok = strchr(p, '/');
	if (!tok)
	{
	    debug(DEBUG_APPERROR, "parse error: expecting / in root");
	    goto out_free_err;
	}
	
	memset(port, 0, sizeof(port));
	memcpy(port, p, tok - p);

	p = tok;
    }
    else
    {
	strcpy_a(port, "2401", 8);
    }

    /* the line from .cvspass is fully qualified, so rebuild */
    snprintf(full_root, PATH_MAX, ":pserver:%s@%s:%s%s", user, server, port, p);
    get_cvspass(pass, full_root, BUFSIZ);

    debug(DEBUG_TCP, "user:%s server:%s port:%s pass:%s full_root:%s", user, server, port, pass, full_root);

    if ((ctx->read_fd = tcp_create_socket(REUSE_ADDR)) < 0)
	goto out_free_err;

    ctx->write_fd = dup(ctx->read_fd);

    if (tcp_connect(ctx->read_fd, server, atoi(port)) < 0)
	goto out_close_err;
    
    send_string(ctx, "BEGIN AUTH REQUEST\n");
    send_string(ctx, "%s\n", p);
    send_string(ctx, "%s\n", user);
    send_string(ctx, "%s\n", pass);
    send_string(ctx, "END AUTH REQUEST\n");

    if (!read_response(ctx, "I LOVE YOU"))
	goto out_close_err;

    strcpy_a(ctx->root, p, PATH_MAX);
    ctx->is_pserver = 1;

    return ctx;

 out_close_err:
    close(ctx->read_fd);
 out_free_err:
    free(ctx);
    return NULL;
}
static int
autodrm_response (Dbptr db)
{

    Dbptr           dbstage;
    static Hook    *hook = 0;
    char            sta[MAX_STA_SIZE],
                    chan[MAX_CHAN_SIZE];
    double          time,
                    endtime;
    long            stageid;
    char           *s;
    Response       *response;
    Response_group *group;
    char            iunits[96],
                    ounits[96];
    char            gtype[100];
    long            i,
                    j;
    Paz            *paz;
    Fir            *fir;
    Fap            *fap;
    Fap2           *fap2;
    FILE           *file;
    double          samprate,
                    gnom,
                    gcalib;
    double          calper=0.0;
    long            decifac;
    char            dir[100],
                    dfile[100];
    char            filename[STRSZ];
    long            nmatches;
    int             errors = 0;
    Tbl            *tbl,
                   *stbl;
    double          mintime=0,
                    maxtime=0;
    char            segtype;
    static Tbl     *keys1 = 0,
                   *keys2 = 0;

    if (keys1 == 0) {
	keys1 = strtbl ("sta", "chan", "time", NULL);
	keys2 = strtbl ("sta", "chan", "time::endtime", NULL);
    }
    dbstage = dblookup (db, 0, "stage", 0, 0);
    nmatches = dbmatches (db, dbstage, &keys1, &keys2, &hook, &tbl);

    switch (nmatches) {
      case dbINVALID:
      case 0:
	dbgetv (db, 0, "sta", sta, "chan", chan, "time", &time, NULL);
	complain (0, "Can't match record for %s:%s @ %s in stage table",
		  sta, chan, s = strydtime (time));
	free (s);
	errors++;
	break;

      default:
	stbl = newtbl (maxtbl (tbl));
	for (i = 0; i < nmatches; i++) {
	    dbstage.record = (long) gettbl (tbl, i);
	    dbgetv (dbstage, 0,
		    "stageid", &stageid,
		    "time", &time,
		    "endtime", &endtime,
		    NULL);
	    if (i == 0) {
		mintime = time;
		maxtime = endtime;
	    } else {
		mintime = MAX (time, mintime);
		maxtime = MIN (endtime, maxtime);
	    }
	    settbl (stbl, stageid - 1, (char *) i);
	}
	if (maxtbl (tbl) != maxtbl (stbl)) {
	    dbgetv (db, 0, "sta", sta, "chan", chan, "time", &time, NULL);
	    complain (0, "stageid numbers for %s:%s @ %s don't add up.",
		      sta, chan, s = strydtime (time));
	    free (s);
	    errors++;
	} else {
	    errors += write_cal2 (db, mintime, maxtime, &calper);

	    for (i = 0; i < nmatches; i++) {
		j = (long) gettbl (stbl, i);
		dbstage.record = (long) gettbl (tbl, j);
		dbgetv (dbstage, 0,
			"sta", sta,
			"chan", chan,
			"time", &time,
			"endtime", &endtime,
			"stageid", &stageid,
			"decifac", &decifac,
			"samprate", &samprate,
			"gnom", &gnom,
			"gcalib", &gcalib,
			"dir", dir,
			"dfile", dfile,
			"gtype", gtype,
			"iunits", iunits,
			"ounits", ounits,
			NULL);

		if (gcalib > 0.0) {
		    gnom *= gcalib;
		} else if (gcalib < 0.0) {
		    complain (0, "gcalib = %10.3f < 0. is invalid for %s:%s @ %s.\n",
			      gcalib, sta, chan, s = strydtime (time));
		    free (s);
		    errors++;
		}
		if (*dir != '-' || *dfile != '-') {
		    long            mark;
		    dbextfile (dbstage, "stage", filename);
		    mark = elog_mark ();
		    elog_log (0, "response file is '%s'", filename);
		    if ((file = fopen (filename, "r")) == 0
			    || read_response (file, &response) < 0) {
			register_error (0,
			      "Can't read response file %s  for %s_%s @ %s",
				 filename, sta, chan, s = strydtime (time));
			free (s);
			fclose (file);
			errors++;
		    } else {
			fclose (file);
			if (response->ngroups > 1) {
			    register_error (0,
			      "stage response file %s has %d stages, not 1",
					    filename, response->ngroups);
			    errors++;
			} else {

			    group = response->groups;

			    switch (group->id) {

			      case PAZ:
				/* The normalization frequency chosen in the
				 * response file may not necessarily be the
				 * same as the one chosen by calibration
				 * table for insertion into the seed volumes.
				 * Consequently, we have to adjust the
				 * specified gnom to be correct for the seed
				 * normalization frequency.  Since the gain
				 * is
				 * 
				 * G(f) = gnom_db * A_response_file * P(f) =
				 * gnom_seed * A_seed * P(f)
				 * 
				 * We have
				 * 
				 * gnom_seed = gnom_db * A_response_file /
				 * A_seed
				 * 
				 * gnom_db is just the gnom from the stage
				 * table. A_response_file is the
				 * normalization from the response file, left
				 * in the stage structure. Below, we
				 * calculate A_seed by setting
				 * A_response_file to 1.0.
				 * 
				 */

				paz = (Paz *) group->pvt;
				for (j = 0; j < strlen (iunits); j++) {
				    iunits[j] = tolower (iunits[j]);
				}
				s = getarr (Segtype, iunits);
				if (s == 0) {
				    segtype = 'D';
				} else {
				    segtype = *s;
				}
				adwrite_paz (stageid, 0, gnom, segtype, ounits, paz);
				break;

			      case IIR:
				paz = (Paz *) group->pvt;
				for (j = 0; j < strlen (iunits); j++) {
				    iunits[j] = tolower (iunits[j]);
				}
				s = getarr (Segtype, iunits);
				if (s == 0) {
				    segtype = 'D';
				} else {
				    segtype = *s;
				}
				adwrite_paz (stageid, 1, gnom, segtype, ounits, paz);
				break;

			      case FIR:
				fir = (Fir *) group->pvt;
				errors += adwrite_fir (stageid, gnom, fir);
				break;

			      case FAP:
				fap = (Fap *) group->pvt;
				errors += adwrite_fap (stageid, ounits, fap);
				break;

			      case FAP2:
				fap2 = (Fap2 *) group->pvt;
				errors += adwrite_fap2 (stageid, ounits, fap2);
				break;


			      default:
				complain (0, "Unknown filter type %d in response file %s\n",
					  group->id, filename);
				errors++;
				break;

			    }
			}
		    }
		    elog_flush (mark, 0);
		} else {
		    char           *desc = "";

		    if (gcalib > 0.0) {
			gnom *= gcalib;
		    } else if (gcalib < 0.0) {
			complain (0, "gcalib = %10.3f < 0. is an invalid value.\n", gcalib);
			errors++;
		    }
		    if (strcmp (gtype, "digitizer") == 0
		    /* following hack for psd2db */
			    || strcmp (gtype, "sensor") == 0) {
			fprintf (stdout, "DIG2 %2ld %15.8e %11.5f %s\n",
				 stageid, gnom, samprate, desc);
		    } else if (strcmp (gtype, "amplifier") == 0) {
			/* no corners */
			fprintf (stdout, "GEN2 %2ld %c %15.8e %7.3f                 0 %s\n",
				 stageid, *ounits, gnom, calper, desc);
		    } else {
			complain (0, "Unrecognized gtype='%s' for %s:%s @ %s",
				  gtype, sta, chan, s = strydtime (time));
			free (s);
			errors++;
		    }
		}
	    }
	}
	freetbl (stbl, 0);
	break;

    }
    freetbl (tbl, 0);
    return errors;
}
Esempio n. 14
0
int main(int argc, char ** argv)
{
	//port used to connect to socket
	char* server_port = "80";
	//ip address or host name of server http request will be sent to
	char* server_ip = "google.com";
	//socket int used to connect
	int sockfd, rc;
	//used to store formatted http request
	char * memcache_req;
	struct addrinfo hints, *server;
	char *message = "";
	//bytes received from server
	int bytes_received = -1;
	//data received from http request--will be printed out to user
	char * recv_data = (char *)malloc(sizeof(char*)*1000);
	int o;
	char * cmd;
	char * key;
	char * value;
	int num_bytes;
	char * memcache_req2;
	size_t len = 0;
        /* Command line args:
                -p port
                -h host name or IP
		-m message (specific page you are requesting.  For ex, when
		   requesting www.cs.gwu.edu/research, the message would be
		   research.)
        */
        while ((o = getopt (argc, argv, "p:h:c:k:v:")) != -1) {
                switch(o){
                case 'p':
                        server_port = optarg;
                        break;
                case 'h':
                        server_ip = optarg;
                        break;
                case 'c':
                        cmd = optarg;
                        break;
		case 'k':
			key = optarg;
			break;
		case 'v':
			value = optarg;
			break;
                case '?':
                        if(optopt == 'p' || optopt == 'h' ) {
                                fprintf (stderr, "Option %c requires an argument.\n", optopt);
                        }
                        else {
                                fprintf (stderr, "Unknown argument: %c.\n", optopt);
                        }
                        break;
                }
        }

	if(cmd[0] == 's'){

		memcache_req = malloc(sizeof(cmd) + sizeof(key) + sizeof(num_bytes) + 14);
		num_bytes = strlen(value);
		sprintf(memcache_req, "%s %s 0 0 %d\r\n", cmd, key, num_bytes);
		memcache_req2 = malloc(sizeof(value)+5);
		sprintf(memcache_req2, "%s\r\n", value);
		printf("%s\n",memcache_req);
		printf("%s\n",memcache_req2);
		//printf("test1\n");
	}
	else{
		memcache_req = malloc(sizeof(cmd) + sizeof(key) +6);
		sprintf(memcache_req, "%s %s\r\n", cmd, key);
		//printf("%s\n",memcache_req);
	//	printf("testing2\n");
	}
	//printf("server_ip: %s   port: %s\n", server_ip, server_port);

        /* The hints struct is used to specify what kind of server info we are looking for */
        memset(&hints, 0, sizeof hints);
        hints.ai_family = AF_INET;
        hints.ai_socktype = SOCK_STREAM; /* or SOCK_DGRAM */

        /* getaddrinfo() gives us back a server address we can connect to.
           It actually gives us a linked list of addresses, but we'll just use the first.
         */
        if (rc = getaddrinfo(server_ip, server_port, &hints, &server) != 0) {
                perror(gai_strerror(rc));
                exit(-1);
        }
	sockfd = socket(server->ai_family, server->ai_socktype, server->ai_protocol);
	if (sockfd == -1) {
		perror("ERROR opening socket");
		exit(-1);
	}
	//printf("socket created\n");
	rc = connect(sockfd, server->ai_addr, server->ai_addrlen);
	if (rc == -1) {
		perror("ERROR on connect");
		close(sockfd);
		exit(-1);
		// TODO: could use goto here for error cleanup
	}
	//printf("connected\n");
	if(cmd[0]=='s'){
		/* Sends the http request. */
		rc = send(sockfd,memcache_req,strlen(memcache_req), 0);
		if(rc < 0) {
			perror("ERROR on send");
			exit(-1);
		}

		rc = send(sockfd, memcache_req2,strlen(memcache_req2),0);
		if(rc < 0){
			perror("ERROR on send 2nd msg");
			exit(01);
		}
	}
	else{
		rc = send(sockfd,memcache_req,strlen(memcache_req),0);
		if(rc < 0){
			perror("ERROR ON SEND");
			exit(-1);
		}

		num_bytes = read_response(sockfd);

		bytes_received = recv(sockfd, recv_data, 1024, 0);
		printf("%s\n", recv_data);
	}
//default buffer size is 1024.  recv receives the info from the server.
/*	bytes_received = recv(sockfd,recv_data,1024,0);

	while(bytes_received)
	{
		//default buffer size is 1024
		bytes_received = recv(sockfd,recv_data,1024,0);

		if(bytes_received == -1)
		{
			perror("recv");
			exit(1);
		}

		//prints out information to user
		printf("%s\n",recv_data);
		if(bytes_received==0){
			break;
		}
		recv_data[bytes_received] = '\0';
	}
*/
	//closes socket
	out:
		freeaddrinfo(server);
	close(sockfd);

	//printf("Done.\n");
	return 0;

}
Esempio n. 15
0
File: rea.c Progetto: eavgerinos/rea
int main(int argc, char *argv[])
{
	int status, maxfd, i, fd, added;
	struct Client *c;

	memset(clients, 0, sizeof(struct Client *)*MAX_CLIENTS);

	if (argc != 2) {
		fprintf(stderr, "Usage: %s <port>\n", argv[0]);
		exit(EXIT_FAILURE);
	}

	setup_and_listen(argv[1]);

	while(1) {
		FD_ZERO(&rfds);
		FD_ZERO(&wfds);
		FD_SET(server->fd, &rfds);
		maxfd = server->fd;

		for (i = 0; i < MAX_CLIENTS; i++) {
			c = clients[i];

			if (c) {
				if (c->to_reply == 1) {
					FD_SET(c->fd, &wfds);
					c->to_reply = 0;
				} else {
					FD_SET(c->fd, &rfds);
				}

				if (fd > maxfd) {
					maxfd = c->fd;
				}
			}
		}

		/* TODO: also add exception set */
		status = select(maxfd+1, &rfds, &wfds, NULL, NULL);
		if (status < 0) {
			err(EXIT_FAILURE, "Socket select error");
		}

		if (FD_ISSET(server->fd, &rfds)) {
			fd = accept4(server->fd, server->addr->ai_addr, &(server->addr->ai_addrlen), SOCK_NONBLOCK);
			if (fd < 0) {
				if (errno == EAGAIN || errno == EWOULDBLOCK) {
					continue;
				}
				err(EXIT_FAILURE, "Socket accept error");
			}

			added = 0;
			for (i = 0; i < MAX_CLIENTS; i++) {
				if (clients[i] == 0) {
					clients[i] = make_client(fd);
					added = 1;
					if (fd > maxfd) {
						maxfd = fd;
					}
					break;
				}
			}

			if (!added) {
				fprintf(stderr, "Could not find room for client fd: %d\n", fd);
				continue;
			}

			printf("Accepted connection! (fd: %d)\n", fd);

			continue;
		}

		for (i = 0; i < MAX_CLIENTS; i++) {
			c = clients[i];

			if (c == 0) {
				continue;
			}

			if (FD_ISSET(c->fd, &wfds)) {
				respond(c);
			} else if (FD_ISSET(c->fd, &rfds) && c->cstate == CONNECTED) {
				read_response(c);
			}
		}
	}
}
Esempio n. 16
0
static int opensoap_handler(request_rec *r)
{	
	apr_status_t rv = 0;
	char req_id[128];
	char res_id[128];
	int rc = 0;	

#ifdef DEBUG
	ap_log_error(APLOG_MARK, APLOG_NOTICE, rv, NULL, 
		"*** mod *** : start");
#endif
	
	if (strcmp(r->handler, "opensoap")) {
		return DECLINED;
	}
	
	if (r->header_only)
		return HTTP_BAD_REQUEST;
	
	if(r->method_number != M_POST)
		return HTTP_BAD_REQUEST;

	SetProcessInfo();
	WriteLog(8,"mod_opensoap start");
	
	/***** Read Request and Write to File ******/
	rc = write_request(r, req_id);
 	if ((rc == EXIT_FAILURE) || (rc == HTTP_INTERNAL_SERVER_ERROR)) {
		ap_log_error(APLOG_MARK, APLOG_EMERG, rv, NULL, 
			"*** mod_err *** : write_request(r, req_id)");
		return HTTP_INTERNAL_SERVER_ERROR;
	} else if (rc == DSO_TOO_BIG) {
		read_response(r, req_id);
		rc = delete_files(req_id);
	 	if (rc == EXIT_FAILURE) {
			ap_log_error(APLOG_MARK, APLOG_EMERG, rv, NULL, 
				"*** mod_err *** : delete_files(res_id)");
		}		
		return OK;
	}

	/****** Invoke Req_Id and Get Res_ID *******/
	WriteLog(9,"invoke start");

	rc = InvokeOpenSOAPServer(req_id, res_id);
 	if (rc == EXIT_FAILURE) {
		ap_log_error(APLOG_MARK, APLOG_EMERG, rv, NULL, 
			"*** mod_err *** : InvokeOpenSOAPServer(req_id, res_id)");
		return HTTP_INTERNAL_SERVER_ERROR;
	}		

	WriteLog(9,res_id);

#ifdef DEBUG
	ap_log_error(APLOG_MARK, APLOG_NOTICE, rv, NULL, 
		"*** mod *** : InvokeOpenSOAPServer req_id = %s", req_id);
	ap_log_error(APLOG_MARK, APLOG_NOTICE, rv, NULL, 
		"*** mod *** : InvokeOpenSOAPServer res_id = %s", res_id);
#endif

	/******** Load Response form File **********/
	rc = read_response(r, res_id);
 	if ((rc == EXIT_FAILURE) || (rc == HTTP_INTERNAL_SERVER_ERROR)) {
		ap_log_error(APLOG_MARK, APLOG_EMERG, rv, NULL, 
			"*** mod_err *** : read_response(r, res_id)");
		return HTTP_INTERNAL_SERVER_ERROR;
	}		

	/****** Delete Files ******/
	rc = delete_files(req_id);
 	if (rc == EXIT_FAILURE) {
		ap_log_error(APLOG_MARK, APLOG_EMERG, rv, NULL, 
			"*** mod_err *** : delete_files(req_id)");
	}		

	rc = delete_files(res_id);
 	if (rc == EXIT_FAILURE) {
		ap_log_error(APLOG_MARK, APLOG_EMERG, rv, NULL, 
			"*** mod_err *** : delete_files(res_id)");
	}		
	
	WriteLog(8,"mod_opensoap end");

	return OK;
}
Esempio n. 17
0
int mailesmtp_auth_sasl(mailsmtp * session, const char * auth_type,
    const char * server_fqdn,
    const char * local_ip_port,
    const char * remote_ip_port,
    const char * login, const char * auth_name,
    const char * password, const char * realm)
{
#ifdef USE_SASL
  int r;
  char command[SMTP_STRING_SIZE];
  sasl_callback_t sasl_callback[5];
  const char * sasl_out;
  unsigned sasl_out_len;
  const char * mechusing;
  sasl_secret_t * secret;
  int res;
  size_t len;
  char * encoded;
  unsigned int encoded_len;
  unsigned int max_encoded;

  sasl_callback[0].id = SASL_CB_GETREALM;
  sasl_callback[0].proc =  (int (*)(void)) sasl_getrealm;
  sasl_callback[0].context = session;
  sasl_callback[1].id = SASL_CB_USER;
  sasl_callback[1].proc =  (int (*)(void)) sasl_getsimple;
  sasl_callback[1].context = session;
  sasl_callback[2].id = SASL_CB_AUTHNAME;
  sasl_callback[2].proc =  (int (*)(void)) sasl_getsimple;
  sasl_callback[2].context = session;
  sasl_callback[3].id = SASL_CB_PASS;
  sasl_callback[3].proc =  (int (*)(void)) sasl_getsecret;
  sasl_callback[3].context = session;
  sasl_callback[4].id = SASL_CB_LIST_END;
  sasl_callback[4].proc =  NULL;
  sasl_callback[4].context = NULL;

  len = strlen(password);
  secret = malloc(sizeof(* secret) + len);
  if (secret == NULL) {
    res = MAILSMTP_ERROR_MEMORY;
    goto err;
  }
  secret->len = len;
  memcpy(secret->data, password, len + 1);

  session->smtp_sasl.sasl_server_fqdn = server_fqdn;
  session->smtp_sasl.sasl_login = login;
  session->smtp_sasl.sasl_auth_name = auth_name;
  session->smtp_sasl.sasl_password = password;
  session->smtp_sasl.sasl_realm = realm;
  session->smtp_sasl.sasl_secret = secret;

  /* init SASL */
  if (session->smtp_sasl.sasl_conn != NULL) {
    sasl_dispose((sasl_conn_t **) &session->smtp_sasl.sasl_conn);
    session->smtp_sasl.sasl_conn = NULL;
  }
  else {
    mailsasl_ref();
  }

  r = sasl_client_new("smtp", server_fqdn,
      local_ip_port, remote_ip_port, sasl_callback, 0,
      (sasl_conn_t **) &session->smtp_sasl.sasl_conn);
  if (r != SASL_OK) {
    res = MAILSMTP_ERROR_AUTH_LOGIN;
    goto free_secret;
  }

  r = sasl_client_start(session->smtp_sasl.sasl_conn,
      auth_type, NULL, &sasl_out, &sasl_out_len, &mechusing);
  if ((r != SASL_CONTINUE) && (r != SASL_OK)) {
    res = MAILSMTP_ERROR_AUTH_LOGIN;
    goto free_sasl_conn;
  }

  if (sasl_out_len != 0) {
    max_encoded = ((sasl_out_len + 2) / 3) * 4;
    encoded = malloc(max_encoded + 1);
    if (encoded == NULL) {
      res = MAILSMTP_ERROR_MEMORY;
      goto free_sasl_conn;
    }

    r = sasl_encode64(sasl_out, sasl_out_len,
        encoded, max_encoded + 1, &encoded_len);
    if (r != SASL_OK) {
      free(encoded);
      res = MAILSMTP_ERROR_MEMORY;
      goto free_sasl_conn;
    }

    snprintf(command, SMTP_STRING_SIZE, "AUTH %s %s\r\n", auth_type, encoded);

    free(encoded);
  }
  else {
    snprintf(command, SMTP_STRING_SIZE, "AUTH %s\r\n", auth_type);
  }

  r = send_command_private(session, command, 0);
  if (r == -1) {
    res = MAILSMTP_ERROR_STREAM;
    goto free_sasl_conn;
  }

  while (1) {
    r = read_response(session);
    switch (r) {
    case 220:
    case 235:
      res = MAILSMTP_NO_ERROR;
      goto free_sasl_conn;

    case 535:
      res = MAILSMTP_ERROR_AUTH_LOGIN;
      goto free_sasl_conn;

    case 553:
    case 554:
      res = MAILSMTP_ERROR_AUTH_AUTHENTICATION_FAILED;
      goto free_sasl_conn;

    case 334:
      {
        size_t response_len;
        char * decoded;
        unsigned int decoded_len;
        unsigned int max_decoded;
        char * p;

        p = strchr(session->response, '\r');
        if (p != NULL) {
          * p = '\0';
        }
        p = strchr(session->response, '\n');
        if (p != NULL) {
          * p = '\0';
        }

        response_len = strlen(session->response);
        max_decoded = response_len * 3 / 4;
        decoded = malloc(max_decoded + 1);
        if (decoded == NULL) {
          res = MAILSMTP_ERROR_MEMORY;
          goto free_sasl_conn;
        }

        r = sasl_decode64(session->response, response_len,
            decoded, max_decoded + 1, &decoded_len);

        if (r != SASL_OK) {
          free(decoded);
          res = MAILSMTP_ERROR_MEMORY;
          goto free_sasl_conn;
        }

        r = sasl_client_step(session->smtp_sasl.sasl_conn,
            decoded, decoded_len, NULL, &sasl_out, &sasl_out_len);

        free(decoded);

        if ((r != SASL_CONTINUE) && (r != SASL_OK)) {
          res = MAILSMTP_ERROR_AUTH_LOGIN;
          goto free_sasl_conn;
        }

        max_encoded = ((sasl_out_len + 2) / 3) * 4;
        encoded = malloc(max_encoded + 1);
        if (encoded == NULL) {
          res = MAILSMTP_ERROR_MEMORY;
          goto free_sasl_conn;
        }

        r = sasl_encode64(sasl_out, sasl_out_len,
            encoded, max_encoded + 1, &encoded_len);
        if (r != SASL_OK) {
          free(encoded);
          res = MAILSMTP_ERROR_MEMORY;
          goto free_sasl_conn;
        }

        snprintf(command, SMTP_STRING_SIZE, "%s\r\n", encoded);
        r = send_command(session, command);

        free(encoded);

        if (r == -1) {
          res = MAILSMTP_ERROR_STREAM;
          goto free_sasl_conn;
        }
      }
      break;

    default:
      res = auth_map_errors(r);
      goto free_sasl_conn;
    }
  }

  res = MAILSMTP_NO_ERROR;

 free_sasl_conn:
  sasl_dispose((sasl_conn_t **) &session->smtp_sasl.sasl_conn);
  session->smtp_sasl.sasl_conn = NULL;
  mailsasl_unref();
 free_secret:
  free(session->smtp_sasl.sasl_secret);
  session->smtp_sasl.sasl_secret = NULL;
 err:
  return res;
#else
  return MAILSMTP_ERROR_NOT_IMPLEMENTED;
#endif
}
Esempio n. 18
0
int mailsmtp_read_response(mailsmtp * session)
{
  return read_response(session);
}
Esempio n. 19
0
int
main( int argc, char** argv ){
    int argn;
    char* message;
#ifdef DO_RECEIVED
    char* received;
#endif /* DO_RECEIVED */
    char* username;
    char hostname[500];
    char from[1000];
    int status;
    char buf[2000];

    /* Parse args. */
    argv0 = argv[0];
    fake_from = (char*) 0;
    parse_message = 0;
#ifdef DO_MINUS_SP
    server = "127.0.0.1";
    port = SMTP_PORT;
#endif /* DO_MINUS_SP */
    verbose = 0;
    timeout = DEFAULT_TIMEOUT;
    argn = 1;
    if (access("/tmp/_articasend.err", F_OK)==0){
	if (unlink("/tmp/_articasend.err")<0){
		printf("cannot delete file %s\n", "/tmp/_articasend.err");
	  }
    }


    while ( argn < argc && argv[argn][0] == '-' )
	{
	if ( strncmp( argv[argn], "-f", 2 ) == 0 && argv[argn][2] != '\0' )
	    fake_from = &(argv[argn][2]);
	else if ( strcmp( argv[argn], "-t" ) == 0 )
	    parse_message = 1;
#ifdef DO_MINUS_SP
	else if ( strncmp( argv[argn], "-s", 2 ) == 0 && argv[argn][2] != '\0' )
	    server = &(argv[argn][2]);
	else if ( strncmp( argv[argn], "-p", 2 ) == 0 && argv[argn][2] != '\0' )
	    port = atoi( &(argv[argn][2]) );
#endif /* DO_MINUS_SP */
	else if ( strncmp( argv[argn], "-T", 2 ) == 0 && argv[argn][2] != '\0' )
	    timeout = atoi( &(argv[argn][2]) );
	else if ( strcmp( argv[argn], "-v" ) == 0 )
	    verbose = 1;
	else if ( strcmp( argv[argn], "-i" ) == 0 )
	    ;	/* ignore */
	else if ( strcmp( argv[argn], "-oi" ) == 0 )
	    ;	/* ignore */
	else if ( strcmp( argv[argn], "--" ) == 0 )
	    ;	/* ignore */
	else
	    usage();
	++argn;
	}

    username = getlogin();
    if ( username == (char*) 0 )
	{
#ifdef DO_GETPWUID
	struct passwd* pw = getpwuid( getuid() );
	if ( pw == (struct passwd*) 0 )
	    {
	    (void) fprintf( stderr, "%s: can't determine username\n", argv0 );
	    exit( 1 );
	    }
	username = pw->pw_name;
#else /* DO_GETPWUID */
	(void) fprintf( stderr, "%s: can't determine username\n", argv0 );
	exit( 1 );
#endif /* DO_GETPWUID */
	}

    if ( gethostname( hostname, sizeof(hostname) - 1 ) < 0 )
	show_error( "gethostname" );

    if ( fake_from == (char*) 0 )
	(void) snprintf( from, sizeof(from), "%s@%s", username, hostname );
    else
	if ( strchr( fake_from, '@' ) == (char*) 0 )
	    (void) snprintf( from, sizeof(from), "%s@%s", fake_from, hostname );
	else
	    (void) snprintf( from, sizeof(from), "%s", fake_from );

    /* Strip off any angle brackets in the from address. */
    while ( from[0] == '<' )
	(void) strcpy( from, &from[1] );
    while ( from[strlen(from)-1] == '>' )
	from[strlen(from)-1] = '\0';

    message = slurp_message();
#ifdef DO_RECEIVED
    received = make_received( from, username, hostname );
#endif /* DO_RECEIVED */

    (void) signal( SIGALRM, sigcatch );

    (void) alarm( timeout );
    sockfd1 = open_client_socket();

    sockfd2 = dup( sockfd1 );
    sockrfp = fdopen( sockfd1, "r" );
    sockwfp = fdopen( sockfd2, "w" );

    /* The full SMTP protocol is spelled out in RFC821, available at
    ** http://www.faqs.org/rfcs/rfc821.html
    ** The only non-obvious wrinkles:
    **  - The commands are terminated with CRLF, not newline.
    **  - Newlines in the data file get turned into CRLFs.
    **  - Any data lines beginning with a period get an extra period prepended.
    */

    status = read_response();
    if ( status != 220 )
	{
	(void) fprintf(
	    stderr,  "%s: unexpected initial greeting %d\n", argv0, status );
	    myError( "ERROR", "unexpected initial greeting" );
	exit( 1 );
	}

    (void) snprintf( buf, sizeof(buf), "HELO %s", hostname );
    send_command( buf );
    status = read_response();
    if ( status != 250 )
	{
	(void) fprintf(
	    stderr,  "%s: unexpected response %d to HELO command\n",argv0, status );
	    myError( "ERROR", "unexpected response %d to HELO command" );
	exit( 1 );
	}

    (void) snprintf( buf, sizeof(buf), "MAIL FROM:<%s>", from );
    send_command( buf );
    status = read_response();
    if ( status != 250 )
	{
	(void) fprintf(
	    stderr,  "%s: unexpected response %d to MAIL FROM command\n",argv0, status );
	    myError( "ERROR", "unexpected response to MAIL FROM command" );
	exit( 1 );
	}

    got_a_recipient = 0;
    for ( ; argn < argc; ++argn )
	add_recipient( argv[argn], strlen( argv[argn] ) );
    if ( parse_message )
	parse_for_recipients( message );
    if ( ! got_a_recipient )
	{
	(void) fprintf( stderr,  "%s: no recipients found\n", argv0 );
	 myError( "ERROR", "no recipients found" );
	exit( 1 );
	}

    send_command( "DATA" );
    status = read_response();
    if ( status != 354 )
	{
	(void) fprintf(stderr,  "%s: unexpected response %d to DATA command\n",argv0, status );
	myError( "ERROR", "unexpected response to DATA" );
	exit( 1 );
	}

#ifdef DO_RECEIVED
    send_data( received );
#endif /* DO_RECEIVED */
    send_data( message );
    send_done();
    status = read_response();
    if ( status != 250 )
	{
	(void) fprintf(stderr,  "%s: unexpected response %d to DATA\n", argv0, status );
	myError( "ERROR", "unexpected response to DATA" );
	exit( 1 );
	}

    send_command( "QUIT" );
    status = read_response();
    if ( status != 221 )
	(void) fprintf(
	    stderr,  "%s: unexpected response %d to QUIT command - ignored\n",argv0, status );
	    myError( "INFO", "unexpected response to QUIT command - ignored" );

    (void) close( sockfd1 );
    (void) close( sockfd2 );

    exit( 0 );
    }
Esempio n. 20
0
static GstFlowReturn
gst_festival_chain (GstPad * pad, GstObject * parent, GstBuffer * buf)
{
  GstFlowReturn ret = GST_FLOW_OK;
  GstFestival *festival;
  GstMapInfo info;
  guint8 *p, *ep;
  gint f;
  FILE *fd;

  festival = GST_FESTIVAL (parent);

  GST_LOG_OBJECT (festival, "Got text buffer, %" G_GSIZE_FORMAT " bytes",
      gst_buffer_get_size (buf));

  f = dup (festival->info->server_fd);
  if (f < 0)
    goto fail_open;
  fd = fdopen (f, "wb");
  if (fd == NULL) {
    close (f);
    goto fail_open;
  }

  /* Copy text over to server, escaping any quotes */
  fprintf (fd, "(Parameter.set 'Audio_Required_Rate 16000)\n");
  fflush (fd);
  GST_DEBUG_OBJECT (festival, "issued Parameter.set command");
  if (read_response (festival) == FALSE) {
    fclose (fd);
    goto fail_read;
  }

  fprintf (fd, "(tts_textall \"");
  gst_buffer_map (buf, &info, GST_MAP_READ);
  p = info.data;
  ep = p + info.size;
  for (; p < ep && (*p != '\0'); p++) {
    if ((*p == '"') || (*p == '\\')) {
      putc ('\\', fd);
    }

    putc (*p, fd);
  }
  fprintf (fd, "\" \"%s\")\n", festival->info->text_mode);
  fclose (fd);
  gst_buffer_unmap (buf, &info);

  GST_DEBUG_OBJECT (festival, "issued tts_textall command");

  /* Read back info from server */
  if (read_response (festival) == FALSE)
    goto fail_read;

out:
  gst_buffer_unref (buf);
  return ret;

  /* ERRORS */
fail_open:
  {
    GST_ELEMENT_ERROR (festival, RESOURCE, OPEN_WRITE, (NULL), (NULL));
    ret = GST_FLOW_ERROR;
    goto out;
  }
fail_read:
  {
    GST_ELEMENT_ERROR (festival, RESOURCE, READ, (NULL), (NULL));
    ret = GST_FLOW_ERROR;
    goto out;
  }
}
Esempio n. 21
0
void* client(void *arg)
{
  char request[1024];
  int sock, ret, i, len;
  cpu_tick_t start, end;
  int server_num = (int) arg;
  int did_some_io = 1;
  int optval;


  // loop, making requests, & keeping stats
  while( 1 ) {
    state_idle++;
  

    // yield, if we didn't yet, ie, due to socket() or connect() failures
    if( !did_some_io )
      sched_yield();
    did_some_io = 0;


    state_idle--; 
    state_connecting++;

    // new socket
    sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if( sock == -1 ) { 
      if( debug ) printf("client() - error with socket(): %s\n", strerror(errno));
      io_errors++;  //perror("socket"); 
      state_connecting--;
      continue; 
    }

    // turn off TCP linger, to do a quick close of the socket
    if ( 0 ) {
      struct linger linger;
      linger.l_onoff = 1;
      linger.l_linger = 0;
      if (setsockopt (sock, SOL_SOCKET, SO_LINGER, &linger, sizeof (linger)) < 0) {
        if( debug ) printf("client() - error setting SO_LINGER: %s\n", strerror(errno));
        io_errors++;
        state_connecting--;
        continue;
      }
    }


    // make the sockets reusable, so we don't wait as long for the
    // kernel to clean things up, and hence run out of sockets.
    //
    // FIXME: is this only meaningful for server sockets??
    optval = 1;
    if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)) < 0) {
      if( debug ) printf("client() - error setting SO_REUSEADDR: %s\n", strerror(errno));
      io_errors++;
      state_connecting--;
      continue;
    }

    /*
    optval = SEND_BUFFER_SIZE;
    if (setsockopt (sock, SOL_SOCKET, SO_SNDBUF, &optval, sizeof (optval)) < 0)
    {
      if( debug ) printf("client() - error setting SO_SNDBUF: %s\n", strerror(errno));
      io_errors++;
      state_connecting--;
      continue;
    }
    
    optval = RECV_BUFFER_SIZE;
    if (setsockopt (sock, SOL_SOCKET, SO_RCVBUF, &optval, sizeof (optval)) < 0)
    {
      if( debug ) printf("client() - error setting SO_RCVBUF: %s\n", strerror(errno));
      io_errors++;
      state_connecting--;
      continue;
    }
    */

    // Disable the Nagle algorithm so the kernel won't delay our
    // writes waiting for more data.
    if( 1 ) {
      optval = 1;
      //if (setsockopt (sock, IPPROTO_TCP, TCP_NODELAY, &optval, sizeof (optval)) < 0)
      if (setsockopt (sock, SOL_TCP, TCP_NODELAY, &optval, sizeof (optval)) < 0)
      {
        if( debug ) printf("client() - error setting TCP_NODELAY: %s\n", strerror(errno));
        io_errors++;
        state_connecting--;
        continue;
      }
    }

    if ( !bind_port(sock) ) {
      state_connecting--;
      continue;
    }

    // Disable the Nagle algorithm so the kernel won't delay our
    // writes waiting for more data.
    if( 1 ) {
      optval = 1;
      //if (setsockopt (sock, IPPROTO_TCP, TCP_NODELAY, &optval, sizeof (optval)) < 0)
      if (setsockopt (sock, SOL_TCP, TCP_NODELAY, &optval, sizeof (optval)) < 0)
      {
        if( debug ) printf("client() - error setting TCP_NODELAY: %s\n", strerror(errno));
        io_errors++;
        state_connecting--;
        continue;
      }
    }

    // connect
    //output("connecting...\n");
    server_num++; server_num = server_num % num_servers;
    GET_REAL_CPU_TICKS(start);
    ret = connect(sock, (struct sockaddr *)&servers[server_num].addr, sizeof(servers[0].addr));
    GET_REAL_CPU_TICKS(end);
    if( ret < 0 ) { 
      state_connecting--; 
      hist_add(err_connect_hist, HIST_INTERVAL(start,end));

      if( errno == EADDRNOTAVAIL ) {
        addrnotavail++;
      } else {
        io_errors++; 
        if( debug )
          printf("client() - error with connect(): %s\n", strerror(errno));
      }

      GET_REAL_CPU_TICKS(start);
      state_closing++;
      close(sock);
      state_closing--;
      GET_REAL_CPU_TICKS(end);
      hist_add(close_unconnected_hist, HIST_INTERVAL(start,end));

      continue; 
    }
    hist_add(connect_hist, HIST_INTERVAL(start,end));


    // Disable the Nagle algorithm so the kernel won't delay our
    // writes waiting for more data.
    if( 1 ) {
      optval = 1;
      //if (setsockopt (sock, IPPROTO_TCP, TCP_NODELAY, &optval, sizeof (optval)) < 0)
      if (setsockopt (sock, SOL_TCP, TCP_NODELAY, &optval, sizeof (optval)) < 0)
      {
        if( debug ) printf("client() - error setting TCP_NODELAY: %s\n", strerror(errno));
        io_errors++;
        state_connecting--;
        continue;
      }
    }

    state_connecting--;

    // issue requests
    for( i=0; i<nreqs; i++ ) {
      len = snprintf(request, sizeof(request)-1, 
                     "GET /%s/dir%05d/class%d_%d HTTP/1.1\r\n"
                     "Host: %s\r\n"
                     //"User-Agent: Mozilla/4.0 (compatible; MSIE 4.01; windows 98)\r\n"
                     //"Accept: */*\r\n"
                     //"Accept-Encoding: gzip, deflate\r\n"
                     //"Accept-Language: en/us\r\n"
                     //"Connection: Close\r\n"
                     "\r\n", 
                     servers[server_num].url, spec_dir(), spec_class(), spec_file(),
                     servers[server_num].hostname
                     );
      assert(len > 0);

      // note that we did some IO, so this thread has already yielded.
      did_some_io = 1;

      state_writing++;
      GET_REAL_CPU_TICKS(start);
      ret = write( sock, request, len );
      GET_REAL_CPU_TICKS(end);
      hist_add(request_hist, HIST_INTERVAL(start,end));
      state_writing--;

      // we do this here, instead of after connect b/c w/ Capriccio
      // the connect() call seems to always return immediately.
      good_conn++;

      if( len != ret ) {
        // FIXME: for now, don't add anything to the response hist, if we get a failure here
        if( errno == ETIMEDOUT ) {
          conn_timedout++;
        } else {
          if(debug) 
            printf("client() - error writing request: %s\n", strerror(errno));
          io_errors++;
        }
        break;
      }

        //output("reading response...\n");
      state_reading++;
      GET_REAL_CPU_TICKS(start);
      if( read_response( sock ) == 0 )
        requests_completed++;
      else 
        bad_conn++;
      GET_REAL_CPU_TICKS(end);
      hist_add(response_hist, HIST_INTERVAL(start,end));
      state_reading--;
      // FIXME: close the connection on errors?


      // sleep for a second
      if(i < nreqs-1 && sleep_ms > 0) {
        state_idle++;
        GET_REAL_CPU_TICKS(start);
        usleep(sleep_ms*1000);
        GET_REAL_CPU_TICKS(end);
        hist_add(sleep_hist, HIST_INTERVAL(start,end));
        state_idle--;
      }

    }

    //output("closing...\n");
    state_closing++;
    GET_REAL_CPU_TICKS(start);
    close( sock );
    GET_REAL_CPU_TICKS(end);
    hist_add(close_hist, HIST_INTERVAL(start,end));
    state_closing--;
  }

  return NULL;
}
Esempio n. 22
0
int read_dec_files (Tbl *decdef, int *dec_fac, Tbl **decimators)

{
    int i, j, n;
    Response *rsp;
    char string[512];
    FILE *file;

    FIR_decimation *decptr;
    Response *resp;

    resp = (Response *) new_response ();

    if(*decimators == NULL) *decimators = newtbl(0);
    if (resp == NULL) {
        elog_die(0, "read_dec_files: Malloc error on decimation response structure.\n");
        return (0);
    }
    for (i=0,(*dec_fac)=1; i<maxtbl(decdef); i++) {
        int ok;
        char *decfile;
        decfile = gettbl(decdef,i);
        if(!strcmp(decfile,"none") )
        {
            *dec_fac = 1.0;
            decptr = (FIR_decimation *) malloc(sizeof(FIR_decimation));
            if(decptr == NULL)
            {
                elog_notify(0,"Cannot malloc decimation structure for stage %d\n",
                            i);
                return(0);
            }
            decptr->decfac = 1.0;
            decptr->ncoefs = 0;
            decptr->coefs=NULL;
            pushtbl(*decimators,decptr);
            return(2);
        }

        file = fopen(decfile, "r");
        if (file == NULL) {
            elog_notify(0, "read_dec_files: Unable to open response stage file '%s'.\n",
                        decfile);
            return (0);
        }
        if (read_response (file, &rsp)) {
            elog_clear_register(1);
            elog_notify(0, "read_dec_files: read_response() error on stage file '%s'.\n",
                        decfile);
            return (0);
        }
        fclose (file);
        get_response_nstages (rsp, &n);
        for (j=0,ok=0; j<n; j++) {
            int dec_factor, nnum, nden;
            double srate;

            get_response_stage_type (rsp, j, string);
            if (strcmp(string, "fir")) continue;
            get_response_stage_fir_ncoefs (rsp, j, &srate, &dec_factor, &nnum, &nden);
            if (nden > 1) {
                elog_notify(0, "read_dec_files: Dont know how to do IIR filters (%s).\n",
                            decfile);
                return (0);
            }
            if (nnum < 1) {
                elog_notify(0, "read_dec_files: No numerator terms (%s).\n",
                            decfile);
                return (0);
            }
            ok=1;
            (*dec_fac) *= dec_factor;
        }
        if (!ok) {
            elog_notify(0, "read_dec_files: no fir stage on file '%s'.\n",
                        decfile);
            return (0);
        }
        for (j=0; j<n; j++) {
            Response_group *gpi;

            get_response_stage_type (rsp, j, string);
            if (strcmp(string, "fir")) continue;
            gpi = rsp->groups + j;
            if (copy_response_group (gpi, (resp), -1) < 0) {
                elog_notify(0, "read_dec_files: copy_response_group() error.\n");
                return (0);
            }
        }
        free_response (rsp);
    }
    get_response_nstages ((resp), &n);

    for (i=0; i<n; i++) {
        Response_group *gpi;
        int dec_factor, nnum, nden;
        double srate;
        double *coefsi, *coefs_err;
        double *coefdi, *coefd_err;

        decptr = (FIR_decimation *) malloc(sizeof(FIR_decimation));
        if(decptr == NULL)
        {
            elog_notify(0,"Cannot malloc decimation structure for stage %d\n",
                        i);
            return(0);
        }

        gpi = (resp)->groups + i;
        get_response_stage_fir_ncoefs ((resp), i, &srate, &dec_factor, &nnum, &nden);
        get_response_stage_fir_coefs ((resp), i, &nnum, &coefsi, &coefs_err,
                                      &nden, &coefdi, &coefd_err);
        for (j=0; j<nnum/2; j++) if (coefsi[j] != coefsi[nnum-j-1]) break;
        if (j < nnum/2) {
            elog_notify(0, "read_dec_files: Can only do symetrical FIR filters.\n");
            return (0);
        }

        decptr->ncoefs = nnum;
        decptr->decfac = dec_factor;
        decptr->coefs = calloc(nnum,sizeof(float));
        if((decptr->coefs) == NULL)
            elog_die(0,"read_dec_files:  can't alloc filter coef array of length %d\n",nnum);
        for(j=0; j<nnum; j++) decptr->coefs[j] = coefsi[j];
        pushtbl(*decimators,decptr);
    }
    return (1);
}
Esempio n. 23
0
int grdb_sc_loadcss (Dbptr dbin, char *net_expr, char *sta_expr,
        char *chan_expr, double tstart, double tend, 
        int coords, int ir, int orient, Dbptr *dbscgr, Dbptr *dbsc)
{
	Dbptr dbout, db, dbout2;
	char string[1024];
	char string2[1024];
	char sta_wfdisc[32], chan_wfdisc[32];
	int i, j, n, sensor=0, ok;
	Tbl *pat1, *pat2;
	Tbl *sortfields, *groupfields;
	FILE *file;
	Response *resp;
	int is_view=0;
	Dbptr db_to_clear;

	/* Subset the wfdisc by station-channel-time sifters. */

	dbout = dblookup (dbin, 0, "wfdisc", 0, 0);
	strcpy (string, "");
	if (sta_expr) {
		strcpy (string, "( ");
        	sprintf (string2, "sta =~ /%s/", sta_expr);
        	strcat (string, string2);
	}
	if (chan_expr) {
		if (string[0]) strcat (string, " && ");
		else strcpy (string, "( ");
        	sprintf (string2, "chan =~ /%s/", chan_expr);
        	strcat (string, string2);
	}
	if (tstart != 0.0 || tend != 0.0) {
		if (string[0]) strcat (string, " && ");
		else strcpy (string, "( ");
        	sprintf (string2, "(time < %.5f && endtime > %.5f)", tend, tstart);
        	strcat (string, string2);
	}
	if (string[0]) {
		strcat (string, " )");
		dbout = dbsubset (dbout, string, 0);
		is_view=1;
	}
        dbquery (dbout, dbRECORD_COUNT, &n);
        if (n < 1) {
		register_error (0, "grdb_sc_loadcss: No wfdisc rows to process.\n");
		return (-1);
        }

        /* Make the necessary joins and check for completeness. */

        if (coords) {
        	db = dblookup (dbin, 0, "site", 0, 0);
		if(is_view)db_to_clear=dbout;
        	dbout = dbjoin (dbout, db, 0, 0, 1, 0, 0);
		if(is_view) dbfree(db_to_clear);
		is_view=1;
		
        	dbquery (dbout, dbRECORD_COUNT, &n);
        	if (n < 1) {
			register_error (0, "grdb_sc_loadcss: No data rows to process.\n");
			return (-1);
        	}
        	for (dbout.record=0; dbout.record<n; dbout.record++) {
        		if (dbgetv (dbout, 0, "wfdisc.sta", sta_wfdisc,
        				"wfdisc.chan", chan_wfdisc,
        				"site.sta", string, 0) == dbINVALID) {
			    register_error (0, "grdb_sc_loadcss: dbgetv() error while checking site.\n");
			    return (-1);
			}
        		if (coords > 1 && strcmp(string, sta_wfdisc)) {
        			register_error (0, "grdb_sc_loadcss: Cannot find site parameters for %s %s.\n", 
        									sta_wfdisc, chan_wfdisc);
        			return (-1);
        		}
        	}
        }
        if (ir) {
        	db = dblookup (dbin, 0, "sensor", 0, 0);
		if(is_view)db_to_clear=dbout;
        	dbout = dbjoin (dbout, db, 0, 0, 1, 0, 0);
		if(is_view) dbfree(db_to_clear);
		is_view=1;
        	dbquery (dbout, dbRECORD_COUNT, &n);
        	if (n < 1) {
			register_error (0, "grdb_sc_loadcss: No data rows to process.\n");
			return (-1);
        	}
        	for (dbout.record=0; dbout.record<n; dbout.record++) {
        		if (dbgetv (dbout, 0, "wfdisc.sta", sta_wfdisc,
        				"wfdisc.chan", chan_wfdisc,
        				"sensor.sta", string, 0) == dbINVALID) {
			    register_error (0, "grdb_sc_loadcss: dbgetv() error while checking sensor.\n");
			    return (-1);
			}
        		if (ir > 1 && strcmp(string, sta_wfdisc)) {
        			register_error (0, "grdb_sc_loadcss: Cannot find sensor parameters for %s %s.\n", 
        									sta_wfdisc, chan_wfdisc);
        			return (-1);
        		}
        	}
        	sensor = 1;
		if(is_view)db_to_clear=dbout;
        	db = dblookup (dbin, 0, "instrument", 0, 0);
        	dbout = dbjoin (dbout, db, 0, 0, 1, 0, 0);
		if(is_view) dbfree(db_to_clear);
		is_view=1;
        	dbquery (dbout, dbRECORD_COUNT, &n);
        	if (n < 1) {
			register_error (0, "grdb_sc_loadcss: No data rows to process.\n");
			return (-1);
        	}
        	for (dbout.record=0; dbout.record<n; dbout.record++) {
        		if (dbgetv (dbout, 0, "wfdisc.sta", sta_wfdisc,
        				"wfdisc.chan", chan_wfdisc,
        				"sensor.inid", &j,
        				"instrument.insname", string2,
        				"instrument.inid", &i, 0) == dbINVALID) {
			    register_error (0, "grdb_sc_loadcss: dbgetv() error while checking instrument.\n");
			    return (-1);
			}
        		if (ir > 1 && (i != j)) {
        			register_error (0, "grdb_sc_loadcss: Cannot find instrument parameters for %s %s.\n", 
        									sta_wfdisc, chan_wfdisc);
        			return (-1);
        		}
        		if (i >= 0) {
				if (resp_arr == NULL) {
					resp_arr = newarr (0);
					if (resp_arr == NULL) {
        					register_error (0, "grdb_sc_loadcss: newarr() error.\n");
        					return (-1);
					}
				}
				dbextfile (dbout, "instrument", string);
				resp = (Response *) getarr (resp_arr, string);
				if (resp == NULL) {
					file = fopen (string, "r");
					if (file == NULL) {
						if (ir > 1) {
        						register_error (1, "grdb_sc_loadcss: fopen('%s') error.\n", string);
        						return (-1);
						}
					} else {
						if (read_response (file, &resp)) {
        						register_error (0, "grdb_sc_loadcss: read_response('%s') error.\n", string);
        						return (-1);
						}
						fclose (file);
						resp->insname = strdup(string2);
					}
					setarr (resp_arr, string, resp);
				}
			}
        	}
        }
        if (orient) {
        	ok = 1;
		if(is_view)db_to_clear=dbout;
        	db = dblookup (dbin, 0, "sitechan", 0, 0);
        	dbout2 = dbjoin (dbout, db, 0, 0, 1, 0, 0);
		is_view=1;
        	dbquery (dbout2, dbRECORD_COUNT, &n);
        	if (n < 1) {
        		ok = 0;
        	} else {
        		for (dbout2.record=0; dbout2.record<n; dbout2.record++) {
        			dbgetv (dbout2, 0, "wfdisc.sta", sta_wfdisc,
        				"wfdisc.chan", chan_wfdisc,
        				"sitechan.sta", string, 0);
        			if (strcmp(string, sta_wfdisc)) {
        				ok = 0;
        				break;
        			}
        		}
		}
		if (ok) {
			dbout = dbout2;
			if(is_view) dbfree(db_to_clear);
		} else {
			if (!sensor) {
        			db = dblookup (dbin, 0, "sensor", 0, 0);
				if(is_view)db_to_clear=dbout;
	       			dbout = dbjoin (dbout, db, 0, 0, 1, 0, 0);
				if(is_view) 
				{
					dbfree(dbout2);
					dbfree(db_to_clear);
				}
				is_view=1;
        			dbquery (dbout, dbRECORD_COUNT, &n);
        			if (n < 1) {
					register_error (0, "grdb_sc_loadcss: No data rows to process.\n");
					return (-1);
        			}
        			for (dbout.record=0; dbout.record<n; dbout.record++) {
        				if (dbgetv (dbout, 0, "wfdisc.sta", sta_wfdisc,
        						"wfdisc.chan", chan_wfdisc,
        						"sensor.sta", string, 0) == dbINVALID) {
			    			register_error (0, "grdb_sc_loadcss: dbgetv() error while checking sensor.\n");
			    			return (-1);
					}
        				if (orient > 1 && strcmp(string, sta_wfdisc)) {
        					register_error (0, "grdb_sc_loadcss: Cannot find sensor parameters for %s %s.\n", 
        											sta_wfdisc, chan_wfdisc);
        					return (-1);
        				}
        			}
			}
        		db = dblookup (dbin, 0, "sitechan", 0, 0);
        		pat1 = newtbl(1);
        		if (pat1 == NULL) {
        			register_error (0, "grdb_sc_loadcss: newtbl() error.\n");
        			return (-1);
        		}
        		pat2 = newtbl(1);
        		if (pat2 == NULL) {
        			register_error (0, "grdb_sc_loadcss: newtbl() error.\n");
        			return (-1);
        		}
			if(is_view)db_to_clear=dbout;
        		settbl (pat1, 0, strdup("sensor.chanid"));
        		settbl (pat2, 0, strdup("sitechan.chanid"));
        		dbout = dbjoin (dbout, db, &pat1, &pat2, 1, 0, 0);
			if(is_view) dbfree(db_to_clear);
			is_view=1;
        		freetbl (pat1, free);
        		freetbl (pat2, free);
        		dbquery (dbout, dbRECORD_COUNT, &n);
        		if (n < 1) {
				register_error (0, "grdb_sc_loadcss: No data rows to process.\n");
				return (-1);
        		} else {
        			for (dbout.record=0; dbout.record<n; dbout.record++) {
        				if (dbgetv (dbout, 0, "wfdisc.sta", sta_wfdisc,
        					"wfdisc.chan", chan_wfdisc,
        					"sitechan.sta", string, 0) == dbINVALID) {
			    		   register_error (0, "grdb_sc_loadcss: dbgetv() error while checking sitechan.\n");
			    		   return (-1);
					}
        				if (orient > 1 && strcmp(string, sta_wfdisc)) {
        					register_error (0, "grdb_sc_loadcss: Cannot find sitechan parameters for %s %s.\n", 
        											sta_wfdisc, chan_wfdisc);
        					return (-1);
        				}
        			}
			}
		}
        }

        /* Sort and group the output view. */

	if(is_view)db_to_clear=dbout;
	sortfields = newtbl (3);
	if (sortfields == NULL) {
		register_error (0, "grdb_sc_loadcss: newtbl() error.\n");
		return (-1);
	}
	settbl (sortfields, 0, strdup("wfdisc.sta"));
	settbl (sortfields, 1, strdup("wfdisc.chan"));
	settbl (sortfields, 2, strdup("wfdisc.time"));
        *dbsc = dbsort (dbout, sortfields, 0, 0);
	if(is_view) dbfree(db_to_clear);
	groupfields = newtbl (2);
	if (groupfields == NULL) {
		register_error (0, "grdb_sc_loadcss: newtbl() error.\n");
		return (-1);
	}
	settbl (groupfields, 0, strdup("sta"));
	settbl (groupfields, 1, strdup("chan"));
	*dbscgr = dbgroup (*dbsc, groupfields, 0, 1);
	freetbl (sortfields, free);
	freetbl (groupfields, free);

	/* Normal exit */

	return (0);
}
Esempio n. 24
0
static int add_adresses(int fd, int if_loopback, unsigned *requests) {
        union {
                struct sockaddr sa;
                struct sockaddr_nl nl;
        } sa = {
                .nl.nl_family = AF_NETLINK,
        };

        union {
                struct nlmsghdr header;
                uint8_t buf[NLMSG_ALIGN(sizeof(struct nlmsghdr)) +
                            NLMSG_ALIGN(sizeof(struct ifaddrmsg)) +
                            RTA_LENGTH(sizeof(struct in6_addr))];
        } request = {
                .header.nlmsg_len = NLMSG_LENGTH(sizeof(struct ifaddrmsg)),
                .header.nlmsg_type = RTM_NEWADDR,
                .header.nlmsg_flags = NLM_F_REQUEST|NLM_F_CREATE|NLM_F_ACK,
                .header.nlmsg_seq = *requests + 1,
        };

        struct ifaddrmsg *ifaddrmsg;
        uint32_t ipv4_address = htonl(INADDR_LOOPBACK);
        int r;

        ifaddrmsg = NLMSG_DATA(&request.header);
        ifaddrmsg->ifa_family = AF_INET;
        ifaddrmsg->ifa_prefixlen = 8;
        ifaddrmsg->ifa_flags = IFA_F_PERMANENT;
        ifaddrmsg->ifa_scope = RT_SCOPE_HOST;
        ifaddrmsg->ifa_index = if_loopback;

        r = add_rtattr(&request.header, sizeof(request), IFA_LOCAL,
                       &ipv4_address, sizeof(ipv4_address));
        if (r < 0)
                return r;

        if (sendto_loop(fd, &request, request.header.nlmsg_len, 0, &sa.sa, sizeof(sa)) < 0)
                return -errno;
        (*requests)++;

        if (!socket_ipv6_is_supported())
                return 0;

        request.header.nlmsg_len = NLMSG_LENGTH(sizeof(struct ifaddrmsg));
        request.header.nlmsg_seq = *requests + 1;

        ifaddrmsg->ifa_family = AF_INET6;
        ifaddrmsg->ifa_prefixlen = 128;

        r = add_rtattr(&request.header, sizeof(request), IFA_LOCAL,
                       &in6addr_loopback, sizeof(in6addr_loopback));
        if (r < 0)
                return r;

        if (sendto_loop(fd, &request, request.header.nlmsg_len, 0, &sa.sa, sizeof(sa)) < 0)
                return -errno;
        (*requests)++;

        return 0;
}

static int start_interface(int fd, int if_loopback, unsigned *requests) {
        union {
                struct sockaddr sa;
                struct sockaddr_nl nl;
        } sa = {
                .nl.nl_family = AF_NETLINK,
        };

        union {
                struct nlmsghdr header;
                uint8_t buf[NLMSG_ALIGN(sizeof(struct nlmsghdr)) +
                            NLMSG_ALIGN(sizeof(struct ifinfomsg))];
        } request = {
                .header.nlmsg_len = NLMSG_LENGTH(sizeof(struct ifinfomsg)),
                .header.nlmsg_type = RTM_NEWLINK,
                .header.nlmsg_flags = NLM_F_REQUEST|NLM_F_ACK,
                .header.nlmsg_seq = *requests + 1,
        };

        struct ifinfomsg *ifinfomsg;

        ifinfomsg = NLMSG_DATA(&request.header);
        ifinfomsg->ifi_family = AF_UNSPEC;
        ifinfomsg->ifi_index = if_loopback;
        ifinfomsg->ifi_flags = IFF_UP;
        ifinfomsg->ifi_change = IFF_UP;

        if (sendto_loop(fd, &request, request.header.nlmsg_len, 0, &sa.sa, sizeof(sa)) < 0)
                return -errno;

        (*requests)++;

        return 0;
}

static int read_response(int fd, unsigned requests_max) {
        union {
                struct sockaddr sa;
                struct sockaddr_nl nl;
        } sa;
        union {
                struct nlmsghdr header;
                uint8_t buf[NLMSG_ALIGN(sizeof(struct nlmsghdr)) +
                            NLMSG_ALIGN(sizeof(struct nlmsgerr))];
        } response;

        ssize_t l;
        socklen_t sa_len = sizeof(sa);
        struct nlmsgerr *nlmsgerr;

        l = recvfrom_loop(fd, &response, sizeof(response), 0, &sa.sa, &sa_len);
        if (l < 0)
                return -errno;

        if (sa_len != sizeof(sa.nl) ||
            sa.nl.nl_family != AF_NETLINK)
                return -EIO;

        if (sa.nl.nl_pid != 0)
                return 0;

        if ((size_t) l < sizeof(struct nlmsghdr))
                return -EIO;

        if (response.header.nlmsg_type != NLMSG_ERROR ||
            (pid_t) response.header.nlmsg_pid != getpid() ||
            response.header.nlmsg_seq >= requests_max)
                return 0;

        if ((size_t) l < NLMSG_LENGTH(sizeof(struct nlmsgerr)) ||
            response.header.nlmsg_len < NLMSG_LENGTH(sizeof(struct nlmsgerr)))
                return -EIO;

        nlmsgerr = NLMSG_DATA(&response.header);

        if (nlmsgerr->error < 0 && nlmsgerr->error != -EEXIST)
                return nlmsgerr->error;

        return response.header.nlmsg_seq;
}

static int check_loopback(void) {
        int r;
        _cleanup_close_ int fd;
        union {
                struct sockaddr sa;
                struct sockaddr_in in;
        } sa = {
                .in.sin_family = AF_INET,
                .in.sin_addr.s_addr = INADDR_LOOPBACK,
        };

        /* If we failed to set up the loop back device, check whether
         * it might already be set up */

        fd = socket(AF_INET, SOCK_DGRAM|SOCK_NONBLOCK|SOCK_CLOEXEC, 0);
        if (fd < 0)
                return -errno;

        if (bind(fd, &sa.sa, sizeof(sa.in)) >= 0)
                r = 1;
        else
                r = errno == EADDRNOTAVAIL ? 0 : -errno;

        return r;
}

int loopback_setup(void) {
        int r, if_loopback;
        union {
                struct sockaddr sa;
                struct sockaddr_nl nl;
        } sa = {
                .nl.nl_family = AF_NETLINK,
        };
        unsigned requests = 0, i;
        _cleanup_close_ int fd = -1;
        bool eperm = false;

        errno = 0;
        if_loopback = (int) if_nametoindex("lo");
        if (if_loopback <= 0)
                return errno ? -errno : -ENODEV;

        fd = socket(PF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
        if (fd < 0)
                return -errno;

        if (bind(fd, &sa.sa, sizeof(sa)) < 0) {
                r = -errno;
                goto error;
        }

        r = add_adresses(fd, if_loopback, &requests);
        if (r < 0)
                goto error;

        r = start_interface(fd, if_loopback, &requests);
        if (r < 0)
                goto error;

        for (i = 0; i < requests; i++) {
                r = read_response(fd, requests);

                if (r == -EPERM)
                        eperm = true;
                else if (r  < 0)
                        goto error;
        }

        if (eperm && check_loopback() < 0) {
                r = -EPERM;
                goto error;
        }

        return 0;

error:
        log_warning("Failed to configure loopback device: %s", strerror(-r));
        return r;
}
Esempio n. 25
0
static WERROR cmd_witness_AsyncNotify(struct rpc_pipe_client *cli,
				      TALLOC_CTX *mem_ctx, int argc,
				      const char **argv)
{
	NTSTATUS status;
	WERROR result = WERR_OK;
	TALLOC_CTX *frame = talloc_stackframe();
	struct policy_handle hnd;
	struct witness_notifyResponse *response = NULL;
	uint32_t timeout;
	bool (*read_response)(TALLOC_CTX*, const uint8_t**) = NULL;

	use_only_one_rpc_pipe_hack(cli);

	if (argc != 2) {
		d_printf("%s <context_handle>\n", argv[0]);
		goto done;
	}

	if (!read_context_handle(argv[1], &hnd)) {
		result = WERR_INVALID_PARAM;
		goto done;
	}

	timeout = dcerpc_binding_handle_set_timeout(cli->binding_handle, UINT32_MAX);
	status = dcerpc_witness_AsyncNotify(cli->binding_handle, frame, hnd,
					    &response, &result);
	dcerpc_binding_handle_set_timeout(cli->binding_handle, timeout);
	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(0, ("dcerpc_witness_AsyncNotify failed, status: %s\n", nt_errstr(status)));
		result = ntstatus_to_werror(status);
		goto done;
	}
	if (!W_ERROR_IS_OK(result)) {
		DEBUG(0, ("dcerpc_witness_AsyncNotify failed, error: %s\n", win_errstr(result)));
		goto done;
	}

	switch(response->message_type) {
	case WITNESS_NOTIFY_RESOURCE_CHANGE:
		d_printf("Resource change");
		read_response = AsyncNotify_Change;
		break;
	case WITNESS_NOTIFY_CLIENT_MOVE:
		d_printf("Client move");
		read_response = AsyncNotify_Move;
		break;
	case WITNESS_NOTIFY_SHARE_MOVE:
		d_printf("Share move");
		read_response = AsyncNotify_Move;
		break;
	case WITNESS_NOTIFY_IP_CHANGE:
		d_printf("IP change");
		read_response = AsyncNotify_Move;
		break;
	default:
		d_printf("Unknown (0x%x)", (int)response->message_type);
	}
	d_printf(" with %d messages\n", response->num_messages);

	if (read_response) {
		unsigned n;
		const uint8_t *pos = response->message_buffer;

		for (n=0; n<response->num_messages; n++) {
			read_response(frame, &pos);
		}
	}

done:
	talloc_free(frame);
	return result;
}
Esempio n. 26
0
int mailesmtp_rcpt(mailsmtp * session,
		    const char * to,
		    int notify,
		    const char * orcpt)
{
  int r;
  char command[SMTP_STRING_SIZE];
  char notify_str[30] = "";
  char notify_info_str[30] = "";

  if (notify != 0 && session->esmtp & MAILSMTP_ESMTP_DSN) {
    if (notify & MAILSMTP_DSN_NOTIFY_SUCCESS)
      strcat(notify_info_str, ",SUCCESS");
    if (notify & MAILSMTP_DSN_NOTIFY_FAILURE)
      strcat(notify_info_str, ",FAILURE");
    if (notify & MAILSMTP_DSN_NOTIFY_DELAY)
      strcat(notify_info_str, ",DELAY");

    if (notify & MAILSMTP_DSN_NOTIFY_NEVER)
      strcpy(notify_info_str, ",NEVER");

    notify_info_str[0] = '=';

    strcpy(notify_str, " NOTIFY");
    strcat(notify_str, notify_info_str);
  }

  if (orcpt && session->esmtp & MAILSMTP_ESMTP_DSN)
    snprintf(command, SMTP_STRING_SIZE, "RCPT TO:<%s>%s ORCPT=%s\r\n",
	     to, notify_str, orcpt);
  else
    snprintf(command, SMTP_STRING_SIZE, "RCPT TO:<%s>%s\r\n", to, notify_str);

  r = send_command(session, command);
  if (r == -1)
    return MAILSMTP_ERROR_STREAM;
  r = read_response(session);

  switch (r) {
  case 250:
    return MAILSMTP_NO_ERROR;

  case 251: /* not local user, will be forwarded */
    return MAILSMTP_NO_ERROR;

  case 550:
  case 450:
    return MAILSMTP_ERROR_MAILBOX_UNAVAILABLE;

  case 551:
    return MAILSMTP_ERROR_USER_NOT_LOCAL;

  case 552:
    return MAILSMTP_ERROR_EXCEED_STORAGE_ALLOCATION;

  case 553:
    return MAILSMTP_ERROR_MAILBOX_NAME_NOT_ALLOWED;

  case 451:
    return MAILSMTP_ERROR_IN_PROCESSING;

  case 452:
    return MAILSMTP_ERROR_INSUFFICIENT_SYSTEM_STORAGE;

  case 503:
    return MAILSMTP_ERROR_BAD_SEQUENCE_OF_COMMAND;

  case 0:
    return MAILSMTP_ERROR_STREAM;

  default:
    return MAILSMTP_ERROR_UNEXPECTED_CODE;
  }
}
int
main_program(int num_channels, int num_connections, const char *server_hostname, int server_port, int timeout)
{
    struct sockaddr_in server_address;
    int main_sd = -1, num_events = 0, i, j, event_mask, channels_per_connection, num, start_time = 0, iters_to_next_summary = 0;
    Connection *connections = NULL, *connection;
    Statistics stats = {0,0,0,0,0};
    int exitcode = EXIT_SUCCESS;
    struct epoll_event events[MAX_EVENTS];
    char buffer[BIG_BUFFER_SIZE];

    info("Subscriber starting up\n");
    info("Subscriber: %d connections to %d channels on server: %s:%d\n", num_connections, num_channels, server_hostname, server_port);

    if ((fill_server_address(server_hostname, server_port, &server_address)) != 0) {
        error2("ERROR host name not found\n");
    }

    if ((main_sd = epoll_create(200 /* this size is not used on Linux kernel 2.6.8+ */)) < 0) {
        error3("Failed %d creating main epoll socket\n", errno);
    }

    if ((connections = init_connections(num_connections, &server_address, main_sd)) == NULL) {
        error2("Failed to create to connections\n");
    }

    stats.requested_connections = num_connections;

    for (i = 0; i < num_connections; i++) {
        connections[i].channel_start = 0;
        connections[i].channel_end = num_channels - 1;
    }

    // infinite loop
    debug("Entering Infinite Loop\n");

    iters_to_next_summary = ITERATIONS_TILL_SUMMARY_PER_TIMEOUT/timeout;

    for(;;) {
        if ((num_events = epoll_wait(main_sd, events, MAX_EVENTS, timeout)) < 0) {
            error3("epoll_wait failed\n");
        }

        for (i = 0; i < num_events; i++) {
            event_mask = events[i].events;
            connection = (Connection *)(events[i].data.ptr);

            if (event_mask & EPOLLHUP) { // SERVER HUNG UP
                debug("EPOLLHUP\n");
                info("Server hung up on conncetion %d. Reconecting...\n", connection->index);
                sleep(1);
                stats.connections--;
                reopen_connection(connection);

                continue;
            }

            if (event_mask & EPOLLERR) {
                debug("EPOLLERR\n");
                info("Server returned an error on connection %d. Reconecting...\n", connection->index);
                stats.connections--;
                reopen_connection(connection);

                continue;
            }

            if (event_mask & EPOLLIN) { // READ
                debug("----------READ AVAILABLE-------\n");

                if (connection->state == CONNECTED) {
                    read_response(connection, &stats, buffer, BIG_BUFFER_SIZE);
                }
            }

            if (event_mask & EPOLLOUT) { // WRITE
                debug("----------WRITE AVAILABLE-------\n");

                if (start_time == 0) {
                    start_time = time(NULL);
                }

                if (connection->state == CONNECTING) {
                    connection->state = CONNECTED;
                    stats.connections++;
                    debug("Connection opened for index=%d\n", connection->index);

                    subscribe_channels(connection, &stats);

                    // remove write flag from event
                    if (change_connection(connection, EPOLLIN | EPOLLHUP) < 0) {
                        error2("Failed creating socket for connection = %d\n", connection->index);
                    }
                }
            }
        }

        if ((iters_to_next_summary-- <= 0)) {
            iters_to_next_summary = ITERATIONS_TILL_SUMMARY_PER_TIMEOUT/timeout;
            summary("Connections=%ld, Messages=%ld BytesRead=%ld Msg/Sec=%0.2f\n", stats.connections, stats.messages, stats.bytes_read, calc_message_per_second(stats.messages, start_time));
        }

        if (stats.connections == 0) {
            num = 0;
            for (j = 0; j < num_connections; j++) {
                if (connections[i].state != CLOSED) {
                    num++;
                    break;
                }
            }

            if (num == 0) {
                exitcode = EXIT_SUCCESS;
                goto exit;
            }
        }
    }

exit:
    if (connections != NULL) free(connections);

    return exitcode;
}
Esempio n. 28
0
File: ocsp.c Progetto: FMayzek/gnupg
/* Construct an OCSP request, send it to the configured OCSP responder
   and parse the response. On success the OCSP context may be used to
   further process the reponse. */
static gpg_error_t
do_ocsp_request (ctrl_t ctrl, ksba_ocsp_t ocsp, gcry_md_hd_t md,
                 const char *url, ksba_cert_t cert, ksba_cert_t issuer_cert)
{
  gpg_error_t err;
  unsigned char *request, *response;
  size_t requestlen, responselen;
  http_t http;
  ksba_ocsp_response_status_t response_status;
  const char *t;
  int redirects_left = 2;
  char *free_this = NULL;

  (void)ctrl;

  if (opt.disable_http)
    {
      log_error (_("OCSP request not possible due to disabled HTTP\n"));
      return gpg_error (GPG_ERR_NOT_SUPPORTED);
    }

  err = ksba_ocsp_add_target (ocsp, cert, issuer_cert);
  if (err)
    {
      log_error (_("error setting OCSP target: %s\n"), gpg_strerror (err));
      return err;
    }

  {
    size_t n;
    unsigned char nonce[32];

    n = ksba_ocsp_set_nonce (ocsp, NULL, 0);
    if (n > sizeof nonce)
      n = sizeof nonce;
    gcry_create_nonce (nonce, n);
    ksba_ocsp_set_nonce (ocsp, nonce, n);
  }

  err = ksba_ocsp_build_request (ocsp, &request, &requestlen);
  if (err)
    {
      log_error (_("error building OCSP request: %s\n"), gpg_strerror (err));
      return err;
    }

 once_more:
  err = http_open (&http, HTTP_REQ_POST, url, NULL,
                   (opt.honor_http_proxy? HTTP_FLAG_TRY_PROXY:0),
                   opt.http_proxy, NULL, NULL, NULL);
  if (err)
    {
      log_error (_("error connecting to '%s': %s\n"), url, gpg_strerror (err));
      xfree (free_this);
      return err;
    }

  es_fprintf (http_get_write_ptr (http),
	      "Content-Type: application/ocsp-request\r\n"
	      "Content-Length: %lu\r\n",
	      (unsigned long)requestlen );
  http_start_data (http);
  if (es_fwrite (request, requestlen, 1, http_get_write_ptr (http)) != 1)
    {
      err = gpg_error_from_errno (errno);
      log_error ("error sending request to '%s': %s\n", url, strerror (errno));
      http_close (http, 0);
      xfree (request);
      xfree (free_this);
      return err;
    }
  xfree (request);
  request = NULL;

  err = http_wait_response (http);
  if (err || http_get_status_code (http) != 200)
    {
      if (err)
        log_error (_("error reading HTTP response for '%s': %s\n"),
                   url, gpg_strerror (err));
      else
        {
          switch (http_get_status_code (http))
            {
            case 301:
            case 302:
              {
                const char *s = http_get_header (http, "Location");

                log_info (_("URL '%s' redirected to '%s' (%u)\n"),
                          url, s?s:"[none]", http_get_status_code (http));
                if (s && *s && redirects_left-- )
                  {
                    xfree (free_this); url = NULL;
                    free_this = xtrystrdup (s);
                    if (!free_this)
                      err = gpg_error_from_errno (errno);
                    else
                      {
                        url = free_this;
                        http_close (http, 0);
                        goto once_more;
                      }
                  }
                else
                  err = gpg_error (GPG_ERR_NO_DATA);
                log_error (_("too many redirections\n"));
              }
              break;

            default:
              log_error (_("error accessing '%s': http status %u\n"),
                         url, http_get_status_code (http));
              err = gpg_error (GPG_ERR_NO_DATA);
              break;
            }
        }
      http_close (http, 0);
      xfree (free_this);
      return err;
    }

  err = read_response (http_get_read_ptr (http), &response, &responselen);
  http_close (http, 0);
  if (err)
    {
      log_error (_("error reading HTTP response for '%s': %s\n"),
                 url, gpg_strerror (err));
      xfree (free_this);
      return err;
    }

  err = ksba_ocsp_parse_response (ocsp, response, responselen,
                                  &response_status);
  if (err)
    {
      log_error (_("error parsing OCSP response for '%s': %s\n"),
                 url, gpg_strerror (err));
      xfree (response);
      xfree (free_this);
      return err;
    }

  switch (response_status)
    {
    case KSBA_OCSP_RSPSTATUS_SUCCESS:      t = "success"; break;
    case KSBA_OCSP_RSPSTATUS_MALFORMED:    t = "malformed"; break;
    case KSBA_OCSP_RSPSTATUS_INTERNAL:     t = "internal error"; break;
    case KSBA_OCSP_RSPSTATUS_TRYLATER:     t = "try later"; break;
    case KSBA_OCSP_RSPSTATUS_SIGREQUIRED:  t = "must sign request"; break;
    case KSBA_OCSP_RSPSTATUS_UNAUTHORIZED: t = "unauthorized"; break;
    case KSBA_OCSP_RSPSTATUS_REPLAYED:     t = "replay detected"; break;
    case KSBA_OCSP_RSPSTATUS_OTHER:        t = "other (unknown)"; break;
    case KSBA_OCSP_RSPSTATUS_NONE:         t = "no status"; break;
    default:                               t = "[unknown status]"; break;
    }
  if (response_status == KSBA_OCSP_RSPSTATUS_SUCCESS)
    {
      if (opt.verbose)
        log_info (_("OCSP responder at '%s' status: %s\n"), url, t);

      err = ksba_ocsp_hash_response (ocsp, response, responselen,
                                     HASH_FNC, md);
      if (err)
        log_error (_("hashing the OCSP response for '%s' failed: %s\n"),
                   url, gpg_strerror (err));
    }
  else
    {
      log_error (_("OCSP responder at '%s' status: %s\n"), url, t);
      err = gpg_error (GPG_ERR_GENERAL);
    }

  xfree (response);
  xfree (free_this);
  return err;
}
// Función que maneja el juego
void manage_game(int fifo_output, int choice, int fifo_input){

		char address_output[] = "/tmp/o_";
	 	char st_out[8];
	 	char *tmp;
	 	int opcion=0, respuesta = 0;
	 	int tx = 0;
	 	/** Establecer conexión con el ouput pipe **/

	 	tmp=malloc(10*sizeof(char));
	 	sprintf(st_out, "%d", choice);
		strcat(address_output,st_out);	
		//free(tmp);		
  		int tmp_fifo = -1;
  		while(tmp_fifo < 0){

			fifo_output = open(address_output,O_WRONLY);		
			tmp_fifo = fifo_output;
		}
		
	//  while(tx!=3){
	  		
	  		char *buf_resp;
	  		buf_resp = malloc(30*sizeof(char));

		  	menu_game();
		  	scanf("%d",&tx);
		  	fflush( stdin );


			int err = write(fifo_output,&tx,sizeof(int));

			if(err < 0){
		 		printf("Failed to write in file \n");
		    }

		    fifo_input = read_response(buf_resp, fifo_input);
	//	}	

		printf ("Esperando rival... \n");
	  	

	  	char *buf_alloc;
		buf_alloc=malloc(20*sizeof(char));	
 		read (fifo_input,buf_alloc,20*sizeof(char));	  
 		printf("%s \n", buf_alloc);


 		printf ("Esperando turno... \n");
	  	int cl = 0;
	  	char *buf;
		buf=malloc(30*sizeof(char));	
 		int r = read (fifo_input,buf,20*sizeof(char));	  
 		if(buf == "Tu turno"){
 			printf("%s \n", buf);
 		}

		while(cl!=5){
		  		char *buf_r;
		  		buf_r = malloc(30*sizeof(char));

			  	printf("Ingrese numero para enviar \n");
			  	scanf("%d",&cl);

				int err = write(fifo_output,&cl,sizeof(int));

				if(err < 0){
			 		printf("Failed to write in file \n");
			    }
			    printf("Esperando resuesta... \n");
			    fifo_input = read_response(buf_r, fifo_input);
			    
		}

	close(fifo_output);

}
Esempio n. 30
0
int main(int argc, char *argv[])
{
    struct sockaddr_in addr;
    int sock;
    int rc;
    FILE *rfp;
    FILE *wfp;
    char buf[1024];
    int tmout = 5*60;   /* 5 minutes should be long enough */

    if (argc < 2)
    {
	fprintf(stderr, "Insufficient arguments\n");
	exit(2);
    }

    /* grok the server name */

    if (!inet_parseaddr(&addr, argv[1], "tcp", "smtp"))
    {
	fprintf(stderr, "Can't parse '%s' as host/service\n", argv[1]);
	exit(2);
    }

    /* lose program name and server name from argv */

    argc -= 2;
    argv += 2;

    /* make the socket */

    sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (sock < 0)
    {
	perror("socket");
	exit(1);
    }

    /* contact server */

    rc = connect(sock, (struct sockaddr *) &addr, sizeof(addr));
    if (rc < 0)
    {
	perror("connect");
	exit(1);
    }

    /* create read and write streams */

    rfp = sock_to_file(sock, "rt");
    wfp = sock_to_file(dup(sock), "wt");

    /* first response; expect 220 from server */

    if (read_response(rfp, tmout) != 220)
    {
	fprintf(stderr,"Unexpected response from server.\n");
	exit(1);
    }

    /* who are we? */

    gethostname(buf, MAXHOSTNAMELEN);

    /* be polite */

    send_command(wfp, "HELO %s", buf);
    read_response(rfp, tmout);

    /* iterate over arguments, emitting a VRFY command for each */
    /* we are echoing the server responses anyway */

    while (argc--)
    {
	send_command(wfp, "VRFY %s", *argv++);
	read_response(rfp, tmout);
    }

    /* all done */

    send_command(wfp, "QUIT");
    read_response(rfp, tmout);

    /* This one should get EOF */

    read_response(rfp, tmout);

    /* close the streams and exit */

    fclose(rfp);
    fclose(wfp);

    return 0;
}