Example #1
0
mrb_value mrb_serialport_open(mrb_state *mrb, mrb_value self) {
  int fd;
  mrb_value mrb_portname = IV_GET("@port_name");
  mrb_value mrb_baud = IV_GET("@baud");
  mrb_value mrb_blocking = IV_GET("@blocking");

  const char *portname = mrb_string_value_cstr(mrb, &mrb_portname);
  unsigned int baud = mrb_fixnum(mrb_baud);

  fd = open(portname, O_RDWR | O_NOCTTY | O_SYNC);
  if (fd < 0) {
    update_error(mrb, self);
    mrb_raise(mrb, E_RUNTIME_ERROR, strerror(errno));
  }
  if (!isatty(fd)) {
    update_error(mrb, self);
    mrb_raise(mrb, E_RUNTIME_ERROR, strerror(errno));
  }
  if (set_interface_attribs(fd, baud, 0)) {
    update_error(mrb, self);
    mrb_raise(mrb, E_RUNTIME_ERROR, strerror(errno));
  }
  if (set_blocking(fd, mrb_bool(mrb_blocking) ? 1 : 0) != 0) {
    IV_SET("@error", mrb_str_new_cstr(mrb, "Could not set blocking behavior"));
    mrb_raise(mrb, E_RUNTIME_ERROR, "Could not set blocking behavior");
  }
  IV_SET("@fd", mrb_fixnum_value(fd));
  return self;
}
Example #2
0
mrb_value mrb_serialport_p_read(mrb_state *mrb, mrb_value self) {
  mrb_value r_buffer_size, r_result;
  ssize_t buf_len;
  char *string = NULL;
  int fd = mrb_fixnum(IV_GET("@fd"));

  mrb_get_args(mrb, "i", &r_buffer_size);
  buf_len = mrb_fixnum(r_buffer_size);
  string = (char *)realloc(string, buf_len * sizeof(char));
  if (!string) {
    free(string);
    string = NULL;
    mrb_raise(mrb, E_RUNTIME_ERROR, "Could not allocate memory");
  }
  bzero(string, buf_len);
  buf_len = read(fd, string, buf_len * sizeof(char));
  if ( buf_len == 0 ) {
    return mrb_nil_value();
  } 
  else if ( buf_len < 0 ) {
    if ( errno == EAGAIN )
      return mrb_nil_value();
    update_error(mrb, self);
    mrb_raise(mrb, E_RUNTIME_ERROR, strerror(errno));
  } 
  r_result = mrb_str_new_cstr(mrb, string);
  free(string);
  return r_result;
}
Example #3
0
mrb_value mrb_serialport_flush(mrb_state *mrb, mrb_value self) {
  int fd = mrb_fixnum(IV_GET("@fd"));
  if (tcflush(fd, TCIOFLUSH) != 0) {
    update_error(mrb, self);
    mrb_raise(mrb, E_RUNTIME_ERROR, strerror(errno));
  }
  return mrb_true_value();
}
Example #4
0
mrb_value mrb_serialport_available(mrb_state *mrb, mrb_value self) {
  int fd = mrb_fixnum(IV_GET("@fd"));
  int bytes_available;
  if (ioctl(fd, FIONREAD, &bytes_available) != 0) {
    update_error(mrb, self);
    mrb_raise(mrb, E_RUNTIME_ERROR, strerror(errno));
  } 
  return mrb_fixnum_value(bytes_available);
}
Example #5
0
mrb_value mrb_serialport_close(mrb_state *mrb, mrb_value self) {
  int fd = mrb_fixnum(IV_GET("@fd"));
  if (close(fd) == 0) {
    IV_SET("@fd", mrb_fixnum_value(-1));
    return mrb_true_value();
  }
  update_error(mrb, self);
  return mrb_false_value();
}
Example #6
0
mrb_value mrb_serialport_p_write(mrb_state *mrb, mrb_value self) {
  char *string;
  size_t l = 0;
  ssize_t res = 0;
  int fd = mrb_fixnum(IV_GET("@fd"));
  
  mrb_get_args(mrb, "s", &string, &l);
  res = write(fd, (char *)string, l);
  if (res < 0) {
    update_error(mrb, self);
    mrb_raise(mrb, E_RUNTIME_ERROR, strerror(errno));
  }
  return mrb_fixnum_value(l);    
}
Example #7
0
mrb_value mrb_serialport_read_char(mrb_state *mrb, mrb_value self) {
  char ch[1];
  ssize_t len = 0;
  int fd = mrb_fixnum(IV_GET("@fd"));
  len = read(fd, ch, sizeof(char));
  if ( len == 0 ) {
      return mrb_nil_value();
  } 
  else if ( len < 0 ) {
    if ( errno == EAGAIN )
      return mrb_nil_value();
    update_error(mrb, self);
    mrb_raise(mrb, E_RUNTIME_ERROR, strerror(errno));
  } 
  return mrb_str_new_cstr(mrb, ch);
}
Example #8
0
File: canl.c Project: CESNET/canl-c
int canl_set_ctx_own_cert(canl_ctx cc, canl_x509 cert, 
        canl_stack_of_x509 chain, canl_pkey key)
{
    glb_ctx *glb_cc = (glb_ctx*) cc;
    int err = 0;

    if (!cc)
        return EINVAL;
    if(!cert)
        return set_error(glb_cc, EINVAL, POSIX_ERROR, "invalid"
                "parameter value");

    err = do_set_ctx_own_cert(glb_cc, cert, chain, key);
    if(err) {
        update_error(glb_cc, "can't set cert or key to context");
    }
        return err;
}
Example #9
0
File: canl.c Project: CESNET/canl-c
//TODO callback and userdata process
int canl_set_ctx_own_cert_file(canl_ctx cc, char *cert, char *key,
        canl_password_callback cb, void *userdata)
{
    glb_ctx *glb_cc = (glb_ctx*) cc;
    int err = 0;

    if (!cc)
        return EINVAL;
    if(!cert ) {
        set_error(glb_cc, EINVAL, POSIX_ERROR, "invalid parameter value");
        return EINVAL;
    }

    err = do_set_ctx_own_cert_file(glb_cc, cert, key);
    if(err) {
        update_error(glb_cc, "can't set cert or key to context");
    }
        return err;
}
Example #10
0
long joy_core::set_error(joy_exception exp)
{
#ifdef DEBUG_PRINTS

  // Get the stack trace
  STACK_FRAMES frames;
  exp.get_stack_frames(frames);

  ostringstream oss_msg;
  char buffer[18];

  oss_msg << "stack frames:" << (int) frames.active_frames << "\n";

  for (unsigned i=0; i < frames.active_frames; i++) {
    sprintf(buffer, "0x%016lx", frames.frames[i]);
    oss_msg << "\tframe:" << dec << setw(2) << setfill('0') << i
	    << "  addr:" << buffer << "\n";
  }

  // Get identification
  oss_msg << "\tPid: " << exp.get_process_id() 
	  << ", Tid: " << exp.get_thread_id() << "\n";

  // Get info from predefined macros
  oss_msg << "\tViolator: " << exp.get_file() 
	  << ":" << exp.get_line()
	  << ", " << exp.get_function() << "\n";

  // Get the internal info
  oss_msg << "\tSource: " << exp.get_source()
	  << ", Code: " << exp.get_code() << "\n";

  oss_msg << "\tInfo: " << exp.get_info() << "\n";

  // Print all info
  debug_printf(oss_msg.str().c_str(), NULL);

#endif // DEBUG_PRINTS

  // Update internal error information
  return update_error(exp);
}
Example #11
0
mrb_value mrb_toggle_dtr(mrb_state *mrb, mrb_value self) {
  int fd = mrb_fixnum(IV_GET("@fd"));
  int val = 0, res = 0;
  int status = 0;
  mrb_get_args(mrb, "i", &val);
  if (val == 0) {
#ifdef TIOCCDTR 
    res = ioctl(fd, TIOCCDTR, NULL);
#elif defined(TIOCM_DTR)
    int iFlags;
    iFlags = TIOCM_DTR;
    res = ioctl(fd, TIOCMBIC, &iFlags);
#else
#error Dunno how to manage DTR
#endif
  }
  else if (val == 1) {
#ifdef TIOCCDTR 
    res = ioctl(fd, TIOCSDTR, NULL);
#elif defined(TIOCM_DTR)
    int iFlags;
    iFlags = TIOCM_DTR;
    res = ioctl(fd, TIOCMBIS, &iFlags);
#else
#error Dunno how to manage DTR
#endif
  }
  else {
    ioctl(fd, TIOCMGET, &status);
    return mrb_fixnum_value(status);  
  }
  if (res != 0) {
    update_error(mrb, self);
    mrb_raise(mrb, E_RUNTIME_ERROR, strerror(errno));
  }
  return mrb_true_value();
}
Example #12
0
File: server.C Project: Amit-DU/dht
void
vnode_impl::update_coords (Coord uc, float ud)
{
  //  warn << myID << " --- starting update -----\n";
  Coord v = uc;
  float rmt_err = uc.err ();

  float actual = ud;
  float expect = me_->coords ().distance_f (uc);

  if (actual >= 0 && actual < 1000000) { //ignore timeouts
    //track our prediction error
    update_error (actual, expect, rmt_err);
    // Work on a copy (including the updated error).
    Coord coords = me_->coords ();

    // force magnitude: > 0 --> stretched
    float grad = expect - actual;
    v.vector_sub (coords);

    float len = v.plane_norm ();
    while (len < 0.0001) {
      for (unsigned int i = 0; i < Coord::NCOORD; i++)
	v.coords[i] = (double)(random () % 400 - 200) / 1.0;
      //if (USING_HT) v.ht += fabs((double)(random () % 10 - 5) / 10.0);
      len = v.plane_norm ();
    }
    len = v.norm ();

    float unit = 1.0 / sqrtf (len);

    // scalar_mult(v, unit) is unit force vector
    // times grad gives the scaled force vector
    v.scalar_mult (unit*grad);

    //timestep is the scaled ratio of our prediction error
    // and the remote node's prediction error
    float pred_err = coords.err ();
    float timestep;
    if (pred_err > 0 && rmt_err > 0)
      timestep = 0.1 * (pred_err)/(pred_err + rmt_err);
    else if (pred_err > 0)
      timestep = 0.0;
    else
      timestep = 1.0;

    v.scalar_mult (timestep);
    //flip sign on height
    v.ht = -v.ht;

    coords.vector_add (v);

#ifdef VIVALDI_DEBUG
    char b[1024];
    snprintf (b, 1024, "coord hop: %f - %f = %f ; len=%f ts=%f (%f %f)\n",
	      expect, actual, grad, len, timestep, pred_err, rmt_err);
    warn << b;
    coords.print ("coords ");
    uc.print ("uc ");
    warn << "----------------\n";
#endif

    if (coords.ht <= 100) coords.ht = 100;
    me_->set_coords (coords);
  } else {
    char b[32];
    snprintf (b, 32, "%f", actual);
    trace << "COORD: ignored actual of " << b << "\n";
  }
}
Example #13
0
int comms_reply(unsigned int port, void *buf, unsigned int size)
{
  
  //return no such port when port doesn't exist
  if (bt(comms_bitmap,port))
  {
    update_port_error(cr3(),-ERR_IPC_NO_SUCH_PORT);
    return -ERR_IPC_NO_SUCH_PORT;
  }
  //return invalid port when port exceeds max ports
  if (port >= COMMS_MAX_PORTS)
  {
    update_error(port,-ERR_IPC_INVALID_PORT);
    return -ERR_IPC_INVALID_PORT;
  }
  //return invalid msg size if buf is less than 1 or exceeds max msg size
  if ((size < 1) | (size > COMMS_MAX_MSG))
  {
    update_error(port,-ERR_IPC_INVALID_MSG_SIZE);
    return -ERR_IPC_INVALID_MSG_SIZE;
  }
  //return invalid buffer when a buffer equals NULL
  if (buf == NULL)
  {
    update_error(port,-ERR_IPC_INVALID_BUFFER);
    return -ERR_IPC_INVALID_BUFFER;
  }
  
  
  //double check if the message is still there
  if (msg_port[port]->queue != NULL)
  {
    //save message into temp
    msg* temp = msg_port[port]->queue;
    
    //check if the sizes are correct
    if (temp->rep_size != size)
    {
      return -ERR_IPC_REPLY_MISMATCH;
    }
        
    //move to next message
    msg_port[port]->queue = msg_port[port]->queue->next;
    //if there is no messages make sure last knows this
    if (msg_port[port] == NULL)
    {
      msg_port[port]->last = NULL;
    }
    
    //switch to client pd
    i386_set_page_directory(temp->pd);
    
    //copy buf into reply address
    copy_4((unsigned int)buf+temp->mult,temp->rep_buf,size/4);
    
    //switch back to server pd
    i386_set_page_directory(msg_port[port]->pcb->pd);
    
    //remove the server page table from the message
    ((page_directory*)(temp->pd))->table[temp->offset] = 0;
    
    //free the memory the message used    
    mem_free(temp);
    
    //unblock the client
    unblock_process(port);
  }else
  {
    //will this happen?    
  } 
  //return OK  
  return OK;
}
Example #14
0
File: canl.c Project: CESNET/canl-c
canl_err_code
canl_io_connect(canl_ctx cc, canl_io_handler io, const char *host, 
        const char *service, int port, gss_OID_set auth_mechs, 
        int flags, canl_principal *peer, struct timeval *timeout)
{
    int err = 0;
    io_handler *io_cc = (io_handler*) io;
    glb_ctx *glb_cc = (glb_ctx*) cc;
    struct _asyn_result ar;
    int i = 0, k;
    int addr_types[] = {AF_INET, AF_INET6}; //TODO ip versions policy?
    int ipver = AF_INET6;
    int j = 0, done;
    struct canl_mech *mech;
    gss_OID oid;

    memset(&ar, 0, sizeof(ar));

    if (!glb_cc) {
        return EINVAL;
    }

    if (!io_cc)
        return set_error(glb_cc, EINVAL, POSIX_ERROR, 
                "IO handler not initialized");

    done = 0;
    for (k = 0; k < sizeof(addr_types)/sizeof(*addr_types); k++) {
        ipver = addr_types[k];
	if (ar.ent) {
	    free_hostent(ar.ent);
	    memset(&ar, 0, sizeof(ar));
	}

        ar.ent = (struct hostent *) calloc (1, sizeof(struct hostent));
        if (ar.ent == NULL)
            return set_error(cc, ENOMEM, POSIX_ERROR, "Not enough memory");

        switch (err = canl_asyn_getservbyname(ipver, &ar, host, NULL)) {
            case NETDB_SUCCESS:
                err = 0;
                break;
            case TRY_AGAIN:
                err = update_error(glb_cc, ETIMEDOUT, POSIX_ERROR,
                        " Timeout reached when connecting to (%s)", host);
		goto end;
            case NETDB_INTERNAL:
		err = update_error(glb_cc, errno, POSIX_ERROR,
                        "Cannot resolve the server hostname (%s)", host);
                continue;
            default:
                err = update_error(glb_cc, err, NETDB_ERROR,
                        "Cannot resolve the server hostname (%s)", host);
                continue;
        }

	j = 0;
	do {
	    if (auth_mechs == GSS_C_NO_OID_SET || auth_mechs->count == 0)
		oid = GSS_C_NO_OID;
	    else
		oid = &auth_mechs->elements[j];

	    mech = find_mech(oid);

	    err = 0;
	    for (i = 0; ar.ent->h_addr_list[i]; i++) {
		void *ctx = NULL;

		if (err == ETIMEDOUT)
		    goto end;

		err = try_connect(glb_cc, io_cc, ar.ent->h_addr_list[i], 
			ar.ent->h_addrtype, port, timeout);//TODO timeout
		if (err)
		    continue;

		err = mech->client_init(glb_cc, &ctx);
		if (err) {
		    canl_io_close(glb_cc, io_cc);
		    continue;
		}

		err = mech->connect(glb_cc, io_cc, ctx, timeout, host);
		if (err) {
		    canl_io_close(glb_cc, io_cc);
		    mech->finish(glb_cc, ctx);
		    ctx = NULL;
                    continue;
                }
                io_cc->conn_ctx = ctx;
                done = 1;
                /* If peer != NULL then client certificate is mandatory*/
                if (peer) {
                    err = mech->get_peer(glb_cc, io_cc, ctx, peer);
                    if (err)
                        goto end;
                }
                
                break;
	    }
	    if (err == ETIMEDOUT)
		goto end;
	    j++;
	} while (auth_mechs != GSS_C_NO_OID_SET && j < auth_mechs->count && !done);

        free_hostent(ar.ent);
        ar.ent = NULL;
	if (done)
	    break;
    }

    if (!done) {
	err = ECONNREFUSED;
	goto end;
    }

    err = 0;

end:
    if (err) /* XXX: rather invent own error */
	err = update_error(glb_cc, ECONNREFUSED, POSIX_ERROR,
		"Failed to make network connection to server %s", host);

    if (ar.ent != NULL)
        free_hostent(ar.ent);

    return err;
}
Example #15
0
File: canl.c Project: CESNET/canl-c
/* XXX use set_error on errors and return a CANL return code */
static int try_connect(glb_ctx *glb_cc, io_handler *io_cc, char *addr,
        int addrtype, int port, struct timeval *timeout)
{
    struct sockaddr_storage a;
    struct sockaddr_storage *p_a=&a;
    socklen_t a_len;
    socklen_t err_len;
    int sock;
    int sock_err;

    struct timeval before,after,to;

    struct sockaddr_in *p4 = (struct sockaddr_in *)p_a;
    struct sockaddr_in6 *p6 = (struct sockaddr_in6 *)p_a;

    memset(p_a, 0, sizeof *p_a);
    p_a->ss_family = addrtype;
    switch (addrtype) {
        case AF_INET:
            memcpy(&p4->sin_addr, addr, sizeof(struct in_addr));
            p4->sin_port = htons(port);
            a_len = sizeof (struct sockaddr_in);
            break;
        case AF_INET6:
            memcpy(&p6->sin6_addr, addr, sizeof(struct in6_addr));
            p6->sin6_port = htons(port);
            a_len = sizeof (struct sockaddr_in6);
            break;
        default:
            return update_error(glb_cc, EINVAL, POSIX_ERROR,
			    "Unsupported address type (%d)", addrtype);
            break;
    }
    
    sock = socket(a.ss_family, SOCK_STREAM, 0);
    if (sock == -1)
        return update_error(glb_cc, errno, POSIX_ERROR,
                "Failed to create network socket");

/* TODO from L&B; do we need it?
    opt = 1;
    setsockopt(sock,IPPROTO_TCP,TCP_NODELAY,&opt,sizeof opt);
*/

    if (timeout) {
        int flags = fcntl(sock, F_GETFL, 0);
        if (fcntl(sock, F_SETFL, flags | O_NONBLOCK) < 0)
            return update_error(glb_cc, errno, POSIX_ERROR,
                    "Failed to set socket file status flags");
        gettimeofday(&before,NULL);
    }

    if (connect(sock,(struct sockaddr *) &a, a_len) < 0) {
        if (timeout && errno == EINPROGRESS) {
            fd_set fds;
            FD_ZERO(&fds);
            FD_SET(sock, &fds);
            /*TODO why don't we use timeout explicitly?*/
            memcpy(&to, timeout, sizeof to);
            gettimeofday(&before, NULL);
            switch (select(sock+1, NULL, &fds, NULL, &to)) {
                case -1: close(sock);
                         return update_error(glb_cc, errno, POSIX_ERROR,
                                 "Connection error");
                case 0: close(sock);
                        timeout->tv_sec = 0; 
                        timeout->tv_usec = 0; 
                        return update_error(glb_cc, errno, POSIX_ERROR,
                                "Connection timeout reached");
            }
            gettimeofday(&after, NULL);
            tv_sub(after, before);
            tv_sub(*timeout, after);

            err_len = sizeof sock_err;
            if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &sock_err, &err_len)) {
                close(sock);
                return update_error(glb_cc, errno, POSIX_ERROR,
                        "Cannost get socket options");
            }
            if (sock_err) {
                close(sock);
                errno = sock_err;
                return update_error(glb_cc, errno, POSIX_ERROR,
                        "Connection error");
            }
        }
        else {
            close(sock);
            return update_error(glb_cc, errno, POSIX_ERROR,
                    "Connection error");
        }
    }

    io_cc->sock = sock;
    return 0;
}