Esempio n. 1
0
/*
 *	Set a port from the request type if we don't already have one
 */
static void radclient_get_port(PW_CODE type, uint16_t *port)
{
	switch (type) {
	default:
	case PW_CODE_ACCESS_REQUEST:
	case PW_CODE_ACCESS_CHALLENGE:
	case PW_CODE_STATUS_SERVER:
		if (*port == 0) *port = getport("radius");
		if (*port == 0) *port = PW_AUTH_UDP_PORT;
		return;

	case PW_CODE_ACCOUNTING_REQUEST:
		if (*port == 0) *port = getport("radacct");
		if (*port == 0) *port = PW_ACCT_UDP_PORT;
		return;

	case PW_CODE_DISCONNECT_REQUEST:
		if (*port == 0) *port = PW_POD_UDP_PORT;
		return;

	case PW_CODE_COA_REQUEST:
		if (*port == 0) *port = PW_COA_UDP_PORT;
		return;

	case PW_CODE_UNDEFINED:
		if (*port == 0) *port = 0;
		return;
	}
}
Esempio n. 2
0
/* Introduce the new format "[address]:port:maxc:hard:weight:prio"
   in addition to the old one.
*/
void setaddress(int server, char *s, int dp, char *proto)
{
	char address[1024], pno[100];
	int n;
	char *format;
	int port;

	if (s[0] == '[') {
		format = "[%999[^]]]:%99[^:]:%d:%d:%d:%d";
	} else {
		format = "%999[^:]:%99[^:]:%d:%d:%d:%d";
	}
	n = sscanf(s, format, address, pno,
		&servers[server].maxc, &servers[server].hard,
		&servers[server].weight, &servers[server].prio);

	if (n > 1) port = getport(pno, proto);
	else port = dp;
	if (n < 3) servers[server].maxc = 0;
	if (n < 4) servers[server].hard = 0;
	if (n < 5) servers[server].weight = 0;
	if (n < 6) servers[server].prio = 0;

	DEBUG(2, "n = %d, address = %s, pno = %d, maxc1 = %d, hard = %d, weight = %d, prio = %d, proto = %s ", \
		n, address, port, servers[server].maxc, \
		servers[server].hard, servers[server].weight, \
		servers[server].prio, proto);

	if (pen_aton(address, &servers[server].addr) == 0) {
		error("unknown or invalid address [%s]", address);
	}
	memset(servers[server].hwaddr, 0, 6);
	pen_setport(&servers[server].addr, port);
}
void set_1003(void) {
  char v_tty[128];
  char v_buf[512];
  int v_ret;
  char msg1[] = { 'A','T','$','Q','C','D','M','G',0x0d,0x0a,0x00 };
  char msg2[] = { 'A','T','^','D','I','S','L','O','G','=','2','5','5',0x0d,0x0a,0x00 };
  char msg3[] = { 0x7e,0x3a,0xa1,0x6e,0x7e,0x00 };

  if(get_mode() != 1404) {
    logging(ANDROID_LOG_ERROR, "modem doesn't have USB-PID 1404!\n");
    exit(1);
  }
  logging(ANDROID_LOG_WARN, "setting modem to USB-PID 1003 ...\n");
  
  getport(v_tty);
  if(v_tty == NULL) {
    logging(ANDROID_LOG_ERROR, "can't find valid tty-port\n");
    exit(1);
  }

  v_ret = write_val(v_tty, msg1);
  v_ret = write_val(v_tty, msg2);
  v_ret = write_val(v_tty, msg3);
  sleep(7);

  v_ret = get_mode();
  if(v_ret != 1003) {
    sprintf(v_buf, "ERROR! Modem was not set to USB-PID 1003, >%d< was reported instead\n", v_ret);
    logging(ANDROID_LOG_ERROR, v_buf);
    exit(1);
  }
  logging(ANDROID_LOG_WARN, "Modem was set to USB-PID 1003 successfuly\n");
  exit(0);
}
Esempio n. 4
0
int diskoperator::list(const managedobject &mo)
{
    //execute dport to get disk physical pci interface
    QMap<QString,int> ports;
    QMap<QString, dfentry> dfentries;
    cmdtool.df(dfentries);
    cmdtool.dport(ports);

    QList<blockdevice*> blocks = mo.blockdev.values();

    QStringList output;
    QString item;
    foreach(blockdevice *block, blocks)
    {
        if (!g_option.show_boot_device && block->isboot)
            continue;
        if (!g_option.show_loop_device && block->isloop)
            continue;
        if (!g_option.show_ram_device && block->isram)
            continue;

        int port = getport(block, ports);

        if (block->isdrive)
        {
            item = QString("%1 disk %2 %3 %4 %5 %6")
                    .arg(port)              //port number
                    .arg(block->device)     //device name
                    .arg(block->id)         //block device id
                    .arg(block->device)     //drive name
                    .arg(block->driveId)    //drive id
                    .arg(block->size);      //block device size
        }
        else
        {
            /*QString drive;
            QString partnum = QString::number(block->partnum);
            if (block->device.endsWith(partnum))
            {
                int length = partnum.length();
                drive = block->device.left(block->device.length() - length);
            }*/
            const dfentry& entry = dfentries.value(block->device);
            item = QString("%1 part %2 %3 %4 %5 %6 %7 %8")
                    .arg(port)
                    .arg(block->device)            //device name
                    .arg(block->id)
                    .arg(block->drive)             //drive name
                    .arg(block->driveId)
                    .arg(block->partsize)
                    .arg(block->mountpoints.size() > 0 ? block->mountpoints[0] : "NONE")
                    .arg(entry.used);
        }
        output.append(item);
    }

    foreach(QString item, output)
    {
        qDebug() << qPrintable(item);
    }
Esempio n. 5
0
void http_init(char *proxy)
{
	char *host, *port;
#ifdef WIN
	WSADATA wsadata;
	if (!WSAStartup(MAKEWORD(2,2), &wsadata))
		http_up = 1;
#else
	signal(SIGPIPE, SIG_IGN);
	http_up = 1;
#endif
	if (proxy)
	{
		host = getserv(proxy);
		port = getport(proxy);
		if (resolve(host, port, &http_proxy))
			http_up = 0;
		else
			http_use_proxy = 1;
		free(host);
		free(port);
	}
	std::stringstream userAgentBuilder;
	userAgentBuilder << "PowderToy/" << SAVE_VERSION << "." << MINOR_VERSION << " ";
	userAgentBuilder << "(" << IDENT_PLATFORM << "; " << IDENT_BUILD << "; M0) ";
	userAgentBuilder << "TPTPP/" << SAVE_VERSION << "." << MINOR_VERSION << "." << BUILD_NUM << IDENT_RELTYPE << "." << SNAPSHOT_ID;
	std::string newUserAgent = userAgentBuilder.str();
	userAgent = new char[newUserAgent.length()+1];
	std::copy(newUserAgent.begin(), newUserAgent.end(), userAgent);
	userAgent[newUserAgent.length()] = 0;
	//"User-Agent: PowderToy/%d.%d (%s; %s; M%d) TPTPP/%d.%d.%d%s.%d\n", SAVE_VERSION, MINOR_VERSION, IDENT_PLATFORM, IDENT_BUILD, 0, SAVE_VERSION, MINOR_VERSION, BUILD_NUM, IDENT_RELTYPE, SNAPSHOT_ID
}
Esempio n. 6
0
// FIXME
void 
get_task_threads(int pid, thread_act_port_array_t *thread_list, mach_msg_type_number_t *thread_count)
{
//	fprintf(stderr, "get_task_threads %x\n", pid);
    task_t port = getport(pid);
    task_threads(port, thread_list, thread_count);
//	fprintf(stderr, "Got %d threads from %d\n", *thread_count, pid);
}
Esempio n. 7
0
static struct rtpp_tnotify_target *
get_tp4wp(struct rtpp_tnotify_set *pvt, struct rtpp_tnotify_wildcard *wp,
  struct sockaddr *ccaddr, struct sockaddr *laddr)
{
    int i;
    struct rtpp_tnotify_target *tp;
    struct sockaddr_in localhost;

    if (ccaddr == NULL || ccaddr->sa_family != AF_INET) {
        /* Request on the unix/IPv6 domain socket, assume it's 127.0.0.1 */
        memset(&localhost, '\0', sizeof(struct sockaddr_in));
        inet_aton("127.0.0.1", &localhost.sin_addr);
        ccaddr = sstosa(&localhost);
        ccaddr->sa_family = AF_INET;
    }
    for (i = 0; i < pvt->tp_len; i++) {
        /* First check against existing targets */
        tp = pvt->tp[i];
        if (tp->socket_name != NULL) {
            /* Only match "automatic" entries */
            continue;
        }
        if (tp->socket_type != wp->socket_type)
            continue;
        if (!ishostseq(ccaddr, sstosa(&tp->remote)))
            continue;
        if (getport(sstosa(&tp->remote)) != wp->port)
            continue;
        return (tp);
    }
    /* Nothing found, crank up a new entry */
    if (pvt->tp_len == RTPP_TNOTIFY_TARGETS_MAX) {
        return (NULL);
    }
    tp = malloc(sizeof(struct rtpp_tnotify_target));
    if (tp == NULL) {
        return (NULL);
    }
    memset(tp, '\0', sizeof(struct rtpp_tnotify_target));
    if (laddr != NULL && laddr->sa_family == ccaddr->sa_family) {
        tp->local = malloc(SA_LEN(laddr));
        if (tp->local == NULL) {
            free(tp);
            return (NULL);
        }
        memcpy(tp->local, laddr, SA_LEN(laddr));
        setanyport(tp->local);
    }
    tp->remote_len = SA_LEN(ccaddr);
    memcpy(&tp->remote, ccaddr, tp->remote_len);
    setport(sstosa(&tp->remote), wp->port);
    tp->socket_type = wp->socket_type;
    tp->connected = 0;
    tp->fd = -1;
    pvt->tp[pvt->tp_len] = tp;
    pvt->tp_len += 1;
    return (tp);
}
Esempio n. 8
0
void getstr(void) {
	s8 buf[1024];
	u16 bufptr = 0;
	memset(buf, 0, sizeof(buf));
	while (1) {
		if (getport(PORT_KEYBOARD_READY) & 0x01) {
			u8 scancode = getport(PORT_KEYBOARD_CHAR);
			if (scancode == 0x1c) {
				docmd(buf);
				bufptr = 0;
				break;
			}
			if (!(scancode & 0x80)) {
				printch(KEYMAP[scancode]);
				buf[bufptr++] = KEYMAP[scancode];
			}
		}
	}
}
Esempio n. 9
0
static int init(int *sd, int *portnr, int *epmd_fd)
{
  char host[HOSTNAMESZ];
  char servernode[NODENAMESZ];
  struct hostent *h; 
  int error = 0;

#ifdef __WIN32__
  WORD wVersionRequested;
  WSADATA wsaData;

  wVersionRequested = MAKEWORD(1, 1);
  if ((error = WSAStartup(wVersionRequested, &wsaData))) {
      fprintf(stderr,"Can't initialize windows sockets: %d",error);
  }        
#endif
 /* get the host name */
  error = gethostname(host,HOSTNAMESZ);
  if (error) {
#ifdef __WIN32__
      fprintf(stderr,"can't find own hostname (error = %ld) !\n",WSAGetLastError());
#else /* not __WIN32__ */
      fprintf(stderr,"can't find own hostname !\n");
#endif
  }
  else {
    /* identify host */
    if (!(h = erl_gethostbyname(host)))
      fprintf(stdout,"can't find own ip address\n");
    else {

      /* get a listen port. 0 means let system choose port number */
      *sd = getlisten(0);
      
      /* what port did we get? */
      /* this call not necessary if we specified port in call to getlisten() */
      *portnr = getport(*sd);
      
      /* make the nodename server@host */
      sprintf(servernode,"%s@%s",SERVER,host);
      
      /* initiate */
      erl_init(NULL,0);

      /* host, alive, alive@host, addr, cookie, creation */
      erl_connect_xinit(host,SERVER,servernode,(Erl_IpAddr)(h->h_addr_list[0]),COOKIE,0);
      
      /* let epmd know we are here */
      *epmd_fd = erl_publish(*portnr);

      return 0;
    } 
  }
  return -1;
}
Esempio n. 10
0
/*
 *	Resolve a port to a request type
 */
static PW_CODE radclient_get_code(uint16_t port)
{
	/*
	 *	getport returns 0 if the service doesn't exist
	 *	so we need to return early, to avoid incorrect
	 *	codes.
	 */
	if (port == 0) return PW_CODE_UNDEFINED;

	if ((port == getport("radius")) || (port == PW_AUTH_UDP_PORT) || (port == PW_AUTH_UDP_PORT_ALT)) {
		return PW_CODE_ACCESS_REQUEST;
	}
	if ((port == getport("radacct")) || (port == PW_ACCT_UDP_PORT) || (port == PW_ACCT_UDP_PORT_ALT)) {
		return PW_CODE_ACCOUNTING_REQUEST;
	}
	if (port == PW_COA_UDP_PORT) return PW_CODE_COA_REQUEST;
	if (port == PW_POD_UDP_PORT) return PW_CODE_DISCONNECT_REQUEST;

	return PW_CODE_UNDEFINED;
}
Esempio n. 11
0
static int
debounce(int x) {
	static const uint8_t mask = 0x07;

	sr[x] = (sr[x] << 1) | getport(x);	// Shift register debouncing
	if ( (sr[x] & mask) == 0 )
		return 0;			// Button pressed
	else if ( (sr[x] & mask) == mask )
		return 1;			// Button released
	else	return 2;			// Bouncing
}
Esempio n. 12
0
int 
virtual_query(int pid, mach_vm_address_t *baseaddr, unsigned int *prot, mach_vm_size_t *size)
{
    
    task_t port = getport(pid);
    //fprintf(stderr, "virtual_query %x %x %x\n", pid, *baseaddr, *size);
    
    // since we are using mach_vm_region we should use the new structures - support both 32 and 64 bits
    mach_msg_type_number_t count = VM_REGION_BASIC_INFO_COUNT_64;
    struct vm_region_basic_info_64 info;
    mach_port_t objectName = MACH_PORT_NULL;
    mach_vm_address_t requested_base = *baseaddr;
    
    kern_return_t result = mach_vm_region(port, baseaddr, size, VM_REGION_BASIC_INFO_64, (vm_region_info_t) &info, &count, &objectName);
	
    // what can go wrong?  
    // No allocated pages at or after the requested addy
    // we just make up one for the rest of memory
    if(result != KERN_SUCCESS){
        //				fprintf(stderr, "[IMPLEMENTATION.C] virtual_query failing case 1\n");
#if __LP64__
        *size = 0xffffffffffffffff - requested_base + 1;
#else
        *size = 0xffffffff - requested_base + 1;
#endif
        *prot = PAGE_NOACCESS;
        return 0;
    }
	
    if (VM_REGION_BASIC_INFO_COUNT_64 != count)
    {
        fprintf(stderr, "vm_region returned a bad info count");
    }
    // Mac scans ahead to the next allocated region, windows doesn't
    // We just make up a region at the base that isn't accessible so that iterating through memory works :/
    // this will bring problems with 64bit binaries because addressing starts at vmaddr 0x0000000100000000
    // and we can have requests for lower addresses
    // FIXME
    if(*baseaddr > requested_base)
    {
        //				fprintf(stderr, "[IMPLEMENTATION.C] virtual_query failing case 2, baseaddr=%p, requested_base=%p\n", (void *)*baseaddr, (void *)requested_base);
        *size = *baseaddr - requested_base;
        *baseaddr = requested_base;
        *prot = PAGE_NOACCESS;
        return 0;
    }
    
    // cool, worked
    *prot = XToWinProtection(info.protection);
    //fprintf(stderr, "Virtual query suceeded\n");
    return 0;
}
Esempio n. 13
0
int 
attach(pid_t pid, mach_port_t *exceptionport)
{
        //fprintf(stderr, "attach %x - calls exn_init\n", pid);
    our_port = -1;  // each time we attach, get a new port
    getport(pid);   // make sure port gets set
    
    *exceptionport = install_debug_port(pid);
    // failure
    if (*exceptionport == 0) return 0;
    // success
    return 1;
}
Esempio n. 14
0
void init(int argc,char ** argv)
{
	port=pwd[0]=notf[0]=0;
	strcpy(pwd,getenv("PWD"));
	if(argv[0][0]!='/')
		sprintf(order,"%s/%s",pwd,argv[0]);
	else sprintf(order,"%s",argv[0]);

	if(argc==1)	{printf("port error\n");exit(0);}
	if(argc>=2)	getport(argv[1]);
	if(argc>=3)	getpwd(argv[2]);
	if(argc>=4)	getnotf(argv[3]);
}
Esempio n. 15
0
int 
virtual_free(int pid, mach_vm_address_t address, mach_vm_size_t size)
{
    int sts;
    vm_map_t port = getport(pid);
	//fprintf(stderr, "virtual_free %x %x %x\n", pid, address, size);
    kern_return_t err = mach_vm_deallocate(port, address, size);
	
    if(err!= KERN_SUCCESS){
        sts = 0;
    } else {
        sts = 1;
    }
    return sts;
}
Esempio n. 16
0
int 
read_memory(int pid, mach_vm_address_t addr, mach_vm_size_t len, char *data)
{
    //		fprintf(stderr, "!read_memory %d %p %x\n", pid, (void *)addr, len);
    mach_vm_size_t nread ;
    vm_map_t port = getport(pid);
	
    mach_vm_read_overwrite(port, addr, len, (mach_vm_address_t)data, &nread);
    if(nread != len){
        //fprintf(stderr, "Error reading memory, requested %d bytes, read %d\n", len, nread);
        //                return 0;  // bad
    }
    /*		if (data != NULL)
     printf("[DEBUG] read %d bytes data is: %x\n", nread, *data);
     */
    return 1;
}
Esempio n. 17
0
char *
allocate(int pid, mach_vm_address_t address, mach_vm_size_t size)
{
    char *data;
	//fprintf(stderr, "allocate %d %d %d\n", pid, address, size);
    vm_map_t port = getport(pid);
    
    kern_return_t err = mach_vm_allocate(port, (mach_vm_address_t*) &data, size, VM_FLAGS_ANYWHERE);
    
    if(err!= KERN_SUCCESS)
    {
        fprintf(stderr,"[IMPLEMENTATION.C] allocate failed!\n");
        data = NULL;
    } 
    //fprintf(stderr, "ALLOCATE RETURNED WITH %x\n", (unsigned int) data);
    return data;
}
Esempio n. 18
0
static struct rtp_packet *
rtpp_socket_rtp_recv(struct rtpp_socket *self, const struct rtpp_timestamp *dtime,
  struct sockaddr *laddr, int port)
{
    struct rtpp_socket_priv *pvt;
    struct rtp_packet *packet;
    struct timeval rtime;
    size_t llen;

    packet = rtp_packet_alloc();
    if (packet == NULL) {
        return NULL;
    }

    pvt = PUB2PVT(self);

    packet->rlen = sizeof(packet->raddr);
    llen = sizeof(packet->_laddr);
    memset(&rtime, '\0', sizeof(rtime));
    packet->size = recvfromto(pvt->fd, packet->data.buf, sizeof(packet->data.buf),
      sstosa(&packet->raddr), &packet->rlen, sstosa(&packet->_laddr), &llen,
      &rtime);

    if (packet->size == -1) {
        rtp_packet_free(packet);
        return (NULL);
    }
    if (llen > 0) {
        packet->laddr = sstosa(&packet->_laddr);
        packet->lport = getport(packet->laddr);
    } else {
        packet->laddr = laddr;
        packet->lport = port;
    }
    if (!timevaliszero(&rtime)) {
        packet->rtime.wall = timeval2dtime(&rtime);
    } else {
        packet->rtime.wall = dtime->wall;
    }
    RTPP_DBG_ASSERT(packet->rtime.wall > 0);
    packet->rtime.mono = dtime->mono;

    return (packet);
}
Esempio n. 19
0
int 
write_memory(int pid, mach_vm_address_t addr, mach_msg_type_number_t len, char *data)
{
    //		fprintf(stderr, "write_memory %d %p %x\n", pid, (void *)addr, len);
    vm_map_t port = getport(pid);
    
    kern_return_t ret = mach_vm_write(port, addr, (vm_offset_t) data, len);
    if(ret != KERN_SUCCESS)
    {
        //fprintf(stderr, "Failed to write to %lx", addr);
        mach_error("mach_vm_write: ", ret);
        if(ret == KERN_PROTECTION_FAILURE)
            fprintf(stderr, "error writing to %p: Specified memory is valid, but does not permit writing\n", (void *)addr);
        if(ret == KERN_INVALID_ADDRESS)
            fprintf(stderr, "error writing to %p: The address is illegal or specifies a non-allocated region\n", (void *)addr);
        return 0;
    }	
    return 1;
}
Esempio n. 20
0
int
httpproxy(struct server *srv,
    struct proxy *pr, struct io *io, int timeout, char **cause)
{
	char	*line;
	int	 port, header;

	if (pr->user != NULL || pr->pass != NULL) {
		xasprintf(cause, "HTTP proxy authentication is not supported");
		return (-1);
	}

	if ((port = getport(srv->port)) < 0) {
		xasprintf(cause, "bad port: %s", srv->port);
		return (-1);
	}

	io_writeline(io, "CONNECT %s:%d HTTP/1.1", srv->host, port);
	io_writeline(io, NULL);

	header = 0;
	for (;;) {
		if (io_pollline(io, &line, timeout, cause) != 1)
			return (-1);

		if (header == 0) {
			if (strlen(line) < 12 ||
			    strncmp(line, "HTTP/", 5) != 0 ||
			    strncmp(line + 8, " 200", 4) != 0) {
				xfree(line);
				xasprintf(cause, "unexpected data: %s", line);
				return (-1);
			}
			header = 1;
		} else {
			if (*line == '\0')
				return (0);
		}

		xfree(line);
	}
}
Esempio n. 21
0
void http_init(char *proxy)
{
  char *host, *port;
#ifdef WIN32
  WSADATA wsadata;
  if(!WSAStartup(MAKEWORD(2,2), &wsadata))
    http_up = 1;
#else
  signal(SIGPIPE, SIG_IGN);
  http_up = 1;
#endif
  if(proxy) {
    host = getserv(proxy);
    port = getport(proxy);
    if(resolve(host, port, &http_proxy))
      http_up = 0;
    else
      http_use_proxy = 1;
    free(host);
    free(port);
  }
}
Esempio n. 22
0
/**
 * Initialize a socket address from a coap URI.
 * @return a pointer to the address or 0 on failure.
 */
sockaddr_t* mc_uri_to_address(sockaddr_t* const addr, char* const uri) {
	sockaddr_t* result;
	char* host;
	uint32_t port;

	/* Skip the scheme. */
	char* current = advanceto(uri, ":");
	current = advanceby(current, "://");
	if (!current) {
		return 0;
	}

	host = getaddress(current);
	if (!host) {
		return 0;
	}

	if (strlen(host) == 0) {
		ms_free(host);
		return 0;
	}

	/* Check and compensate for IP v6 []'s if needed. */
	if (current && (*current == '[')) current += 2;

	current += strlen(host);
	port = getport(current);
	if (port == 0) {
		ms_free(host);
		return 0;
	}

	result = mn_sockaddr_inet_init(addr, host, port);
	ms_free(host);

	return result;
}
Esempio n. 23
0
int 
virtual_protect(int pid, mach_vm_address_t address, mach_vm_size_t size, vm_prot_t type)
{
    vm_map_t port = getport(pid);
    int sts;
    // convert from Windows to OS X protection
    vm_prot_t mac_prot = winToXProtection(type);
        
    kern_return_t err = mach_vm_protect(port, address, size, FALSE, mac_prot);
	
    if(err == KERN_SUCCESS){
        sts = 1;
    } else if(err == KERN_PROTECTION_FAILURE){
        sts = 1;  // hopefully they are setting up to read only
        fprintf(stderr, "[IMPLEMENTATION.C] virtual_protect Failed to protect\n");
    } else if(err == KERN_INVALID_ADDRESS){
        sts = 1;
        fprintf(stderr, "[IMPLEMENTATION.C] virtual_protect The address %p is illegal or specifies a non-allocated region.\n", (void*)address);
    } else {
        fprintf(stderr, "[IMPLEMENTATION.C] virtual_protect Opps, got %d return from vm_protect\n", err);
        sts = 1;  // Probably memory is not allocated.
    }
    return sts;
}
Esempio n. 24
0
int main(int argc, char **argv)
{
	RADIUS_PACKET *req;
	char *p;
	int c;
	int port = 0;
	char *filename = NULL;
	FILE *fp;
	int id;
	int force_af = AF_UNSPEC;

	/*
	 *	We probably don't want to free the talloc autofree context
	 *	directly, so we'll allocate a new context beneath it, and
	 *	free that before any leak reports.
	 */
	TALLOC_CTX *autofree = talloc_init("main");

	id = ((int)getpid() & 0xff);
	fr_debug_flag = 0;

	radlog_dest = L_DST_STDERR;

	set_radius_dir(autofree, RADIUS_DIR);

	while ((c = getopt(argc, argv, "46c:d:D:f:hi:qst:r:S:xXv")) != EOF)
	{
		switch(c) {
		case '4':
			force_af = AF_INET;
			break;
		case '6':
			force_af = AF_INET6;
			break;
		case 'd':
			set_radius_dir(autofree, optarg);
			break;
		case 'D':
			mainconfig.dictionary_dir = talloc_typed_strdup(NULL, optarg);
			break;
		case 'f':
			filename = optarg;
			break;
		case 'q':
			do_output = 0;
			break;
		case 'x':
			debug_flag++;
			fr_debug_flag++;
			break;

		case 'X':
#if 0
		  sha1_data_problems = 1; /* for debugging only */
#endif
		  break;



		case 'r':
			if (!isdigit((int) *optarg))
				usage();
			retries = atoi(optarg);
			break;
		case 'i':
			if (!isdigit((int) *optarg))
				usage();
			id = atoi(optarg);
			if ((id < 0) || (id > 255)) {
				usage();
			}
			break;
		case 's':
			do_summary = 1;
			break;
		case 't':
			if (!isdigit((int) *optarg))
				usage();
			timeout = atof(optarg);
			break;
		case 'v':
			printf("radeapclient: $Id: 20c518ef414933fae3cdf564852c12e483f7c8c9 $ built on " __DATE__ " at " __TIME__ "\n");
			exit(0);
			break;
	       case 'S':
		       fp = fopen(optarg, "r");
		       if (!fp) {
			       fprintf(stderr, "radclient: Error opening %s: %s\n",
				       optarg, fr_syserror(errno));
			       exit(1);
		       }
		       if (fgets(filesecret, sizeof(filesecret), fp) == NULL) {
			       fprintf(stderr, "radclient: Error reading %s: %s\n",
				       optarg, fr_syserror(errno));
			       exit(1);
		       }
		       fclose(fp);

		       /* truncate newline */
		       p = filesecret + strlen(filesecret) - 1;
		       while ((p >= filesecret) &&
			      (*p < ' ')) {
			       *p = '\0';
			       --p;
		       }

		       if (strlen(filesecret) < 2) {
			       fprintf(stderr, "radclient: Secret in %s is too short\n", optarg);
			       exit(1);
		       }
		       secret = filesecret;
		       break;
		case 'h':
		default:
			usage();
			break;
		}
	}
	argc -= (optind - 1);
	argv += (optind - 1);

	if ((argc < 3)  ||
	    ((!secret) && (argc < 4))) {
		usage();
	}

	if (!mainconfig.dictionary_dir) {
		mainconfig.dictionary_dir = DICTDIR;
	}

	/*
	 *	Read the distribution dictionaries first, then
	 *	the ones in raddb.
	 */
	DEBUG2("including dictionary file %s/%s", mainconfig.dictionary_dir, RADIUS_DICTIONARY);
	if (dict_init(mainconfig.dictionary_dir, RADIUS_DICTIONARY) != 0) {
		ERROR("Errors reading dictionary: %s",
		      fr_strerror());
		exit(1);
	}

	/*
	 *	It's OK if this one doesn't exist.
	 */
	int rcode = dict_read(radius_dir, RADIUS_DICTIONARY);
	if (rcode == -1) {
		ERROR("Errors reading %s/%s: %s", radius_dir, RADIUS_DICTIONARY,
		      fr_strerror());
		exit(1);
	}

	/*
	 *	We print this after reading it.  That way if
	 *	it doesn't exist, it's OK, and we don't print
	 *	anything.
	 */
	if (rcode == 0) {
		DEBUG2("including dictionary file %s/%s", radius_dir, RADIUS_DICTIONARY);
	}

	req = rad_alloc(NULL, 1);
	if (!req) {
		fr_perror("radclient");
		exit(1);
	}

#if 0
	{
		FILE *randinit;

		if((randinit = fopen("/dev/urandom", "r")) == NULL)
		{
			perror("/dev/urandom");
		} else {
			fread(randctx.randrsl, 256, 1, randinit);
			fclose(randinit);
		}
	}
	fr_randinit(&randctx, 1);
#endif

	req->id = id;

	/*
	 *	Resolve hostname.
	 */
	if (force_af == AF_UNSPEC) force_af = AF_INET;
	req->dst_ipaddr.af = force_af;
	if (strcmp(argv[1], "-") != 0) {
		char const *hostname = argv[1];
		char const *portname = argv[1];
		char buffer[256];

		if (*argv[1] == '[') { /* IPv6 URL encoded */
			p = strchr(argv[1], ']');
			if ((size_t) (p - argv[1]) >= sizeof(buffer)) {
				usage();
			}

			memcpy(buffer, argv[1] + 1, p - argv[1] - 1);
			buffer[p - argv[1] - 1] = '\0';

			hostname = buffer;
			portname = p + 1;

		}
		p = strchr(portname, ':');
		if (p && (strchr(p + 1, ':') == NULL)) {
			*p = '\0';
			portname = p + 1;
		} else {
			portname = NULL;
		}

		if (ip_hton(hostname, force_af, &req->dst_ipaddr) < 0) {
			fprintf(stderr, "radclient: Failed to find IP address for host %s: %s\n", hostname, fr_syserror(errno));
			exit(1);
		}

		/*
		 *	Strip port from hostname if needed.
		 */
		if (portname) port = atoi(portname);
	}

	/*
	 *	See what kind of request we want to send.
	 */
	if (strcmp(argv[2], "auth") == 0) {
		if (port == 0) port = getport("radius");
		if (port == 0) port = PW_AUTH_UDP_PORT;
		req->code = PW_CODE_AUTHENTICATION_REQUEST;

	} else if (strcmp(argv[2], "acct") == 0) {
		if (port == 0) port = getport("radacct");
		if (port == 0) port = PW_ACCT_UDP_PORT;
		req->code = PW_CODE_ACCOUNTING_REQUEST;
		do_summary = 0;

	} else if (strcmp(argv[2], "status") == 0) {
		if (port == 0) port = getport("radius");
		if (port == 0) port = PW_AUTH_UDP_PORT;
		req->code = PW_CODE_STATUS_SERVER;

	} else if (strcmp(argv[2], "disconnect") == 0) {
		if (port == 0) port = PW_POD_UDP_PORT;
		req->code = PW_CODE_DISCONNECT_REQUEST;

	} else if (isdigit((int) argv[2][0])) {
		if (port == 0) port = getport("radius");
		if (port == 0) port = PW_AUTH_UDP_PORT;
		req->code = atoi(argv[2]);
	} else {
		usage();
	}
	req->dst_port = port;

	/*
	 *	Add the secret.
	 */
	if (argv[3]) secret = argv[3];

	/*
	 *	Read valuepairs.
	 *	Maybe read them, from stdin, if there's no
	 *	filename, or if the filename is '-'.
	 */
	if (filename && (strcmp(filename, "-") != 0)) {
		fp = fopen(filename, "r");
		if (!fp) {
			fprintf(stderr, "radclient: Error opening %s: %s\n",
				filename, fr_syserror(errno));
			exit(1);
		}
	} else {
		fp = stdin;
	}

	/*
	 *	Send request.
	 */
	if ((req->sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
		perror("radclient: socket: ");
		exit(1);
	}

	while(!filedone) {
		if(req->vps) pairfree(&req->vps);

		if ((req->vps = readvp2(NULL, fp, &filedone, "radeapclient:")) == NULL) {
			break;
		}

		sendrecv_eap(req);
	}

	if(do_summary) {
		printf("\n\t   Total approved auths:  %d\n", totalapp);
		printf("\t     Total denied auths:  %d\n", totaldeny);
	}

	talloc_free(autofree);

	return 0;
}
Esempio n. 25
0
/*
 * Check to see if we are sending files to a remote machine. If we are,
 * then try removing files on the remote machine.
 */
void
rmremote(const struct printer *pp)
{
	int i, elem, firstreq, niov, rem, totlen;
	char buf[BUFSIZ];
	void (*savealrm)(int);
	struct iovec *iov;

	if (!pp->remote)
		return;	/* not sending to a remote machine */

	/*
	 * Flush stdout so the user can see what has been deleted
	 * while we wait (possibly) for the connection.
	 */
	fflush(stdout);

	/*
	 * Counting:
	 *	4 == "\5" + remote_queue + " " + person
	 *	2 * users == " " + user[i] for each user
	 *	requests == asprintf results for each request
	 *	1 == "\n"
	 * Although laborious, doing it this way makes it possible for
	 * us to process requests of indeterminate length without
	 * applying an arbitrary limit.  Arbitrary Limits Are Bad (tm).
	 */
	if (users > 0)
		niov = 4 + 2 * users + requests + 1;
	else
		niov = 4 + requests + 1;
	iov = malloc(niov * sizeof *iov);
	if (iov == 0)
		fatal(pp, "out of memory in rmremote()");
	iov[0].iov_base = "\5";
	iov[1].iov_base = pp->remote_queue;
	iov[2].iov_base = " ";
	iov[3].iov_base = all ? "-all" : person;
	elem = 4;
	for (i = 0; i < users; i++) {
		iov[elem].iov_base = " ";
		iov[elem + 1].iov_base = user[i];
		elem += 2;
	}
	firstreq = elem;
	for (i = 0; i < requests; i++) {
		asprintf((char **)&iov[elem].iov_base, " %d", requ[i]);
		if (iov[elem].iov_base == 0)
			fatal(pp, "out of memory in rmremote()");
		elem++;
	}
	iov[elem++].iov_base = "\n";
	for (totlen = i = 0; i < niov; i++)
		totlen += (iov[i].iov_len = strlen(iov[i].iov_base));

	savealrm = signal(SIGALRM, alarmhandler);
	alarm(pp->conn_timeout);
	rem = getport(pp, pp->remote_host, 0);
	(void)signal(SIGALRM, savealrm);
	if (rem < 0) {
		if (from_host != local_host)
			printf("%s: ", local_host);
		printf("connection to %s is down\n", pp->remote_host);
	} else {
		if (writev(rem, iov, niov) != totlen)
			fatal(pp, "Lost connection");
		while ((i = read(rem, buf, sizeof(buf))) > 0)
			(void) fwrite(buf, 1, i, stdout);
		(void) close(rem);
	}
	for (i = 0; i < requests; i++)
		free(iov[firstreq + i].iov_base);
	free(iov);
}
Esempio n. 26
0
int
socks5proxy(struct server *srv,
    struct proxy *pr, struct io *io, int timeout, char **cause)
{
	int	port, auth;
	char	buf[1024], *ptr;
	size_t	len;

	if ((port = getport(srv->port)) < 0) {
		xasprintf(cause, "bad port: %s", srv->port);
		return (-1);
	}

	/* Method selection. */
	auth = pr->user != NULL && pr->pass != NULL;
	buf[0] = 5;
	buf[1] = auth ? 2 : 1;
	buf[2] = 0;	/* 0 = no auth */
	buf[3] = 2;	/* 2 = user/pass auth */
	io_write(io, buf, auth ? 4 : 3);

	if (io_wait(io, 2, timeout, cause) != 0)
		return (-1);
	io_read2(io, buf, 2);
	if (buf[0] != 5) {
		xasprintf(cause, "bad protocol version: %d", buf[0]);
		return (-1);
	}
	if ((buf[1] != 0 && buf[1] != 2) || (auth == 0 && buf[1] == 2)) {
		xasprintf(cause, "unexpected method: %d", buf[1]);
		return (-1);
	}

	/* User/pass negotiation. */
	if (buf[1] == 2) {
		ptr = buf;
		*ptr++ = 5;
		len = strlen(pr->user);
		if (len > 255) {
			xasprintf(cause, "user too long");
			return (-1);
		}
		*ptr++ = len;
		memcpy(ptr, pr->user, len);
		ptr += len;
		len = strlen(pr->pass);
		if (len > 255) {
			xasprintf(cause, "pass too long");
			return (-1);
		}
		*ptr++ = len;
		memcpy(ptr, pr->pass, len);
		ptr += len;
		io_write(io, buf, ptr - buf);

		if (io_wait(io, 2, timeout, cause) != 0)
			return (-1);
		io_read2(io, buf, 2);
		if (buf[0] != 5) {
			xasprintf(cause, "bad protocol version: %d", buf[0]);
			return (-1);
		}
		if (buf[1] != 0) {
			xasprintf(cause, "authentication failed");
			return (-1);
		}
	}

	/* Connect request. */
	ptr = buf;
	*ptr++ = 5;
	*ptr++ = 1; /* 1 = connect */
	*ptr++ = 0; /* reserved */
	*ptr++ = 3; /* 3 = domain name */
	len = strlen(srv->host);
	if (len > 255) {
		xasprintf(cause, "host too long");
		return (-1);
	}
	*ptr++ = len;
	memcpy(ptr, srv->host, len);
	ptr += len;
	*ptr++ = (port >> 8) & 0xff;
	*ptr++ = port & 0xff;
	io_write(io, buf, ptr - buf);

	/* Connect response. */
	if (io_wait(io, 5, timeout, cause) != 0)
		return (-1);
	io_read2(io, buf, 5);
	if (buf[0] != 5) {
		xasprintf(cause, "bad protocol version: %d", buf[0]);
		return (-1);
	}
	switch (buf[1]) {
	case 0:
		break;
	case 1:
		xasprintf(cause, "%d: server failure", buf[1]);
		return (-1);
	case 2:
		xasprintf(cause, "%d: connection not permitted", buf[1]);
		return (-1);
	case 3:
		xasprintf(cause, "%d: network unreachable", buf[1]);
		return (-1);
	case 4:
		xasprintf(cause, "%d: host unreachable", buf[1]);
		return (-1);
	case 5:
		xasprintf(cause, "%d: connection refused", buf[1]);
		return (-1);
	case 6:
		xasprintf(cause, "%d: TTL expired", buf[1]);
		return (-1);
	case 7:
		xasprintf(cause, "%d: command not supported", buf[1]);
		return (-1);
	case 8:
		xasprintf(cause, "%d: address type not supported", buf[1]);
		return (-1);
	default:
		xasprintf(cause, "%d: unknown failure", buf[1]);
		return (-1);
	}

	/* Flush the rest. */
	switch (buf[3]) {
	case 1: /* IPv4 */
		len = 5;
		break;
	case 3: /* host */
		len = buf[4] + 2;
		break;
	case 4: /* IPv6 */
		len = 17;
		break;
	default:
		xasprintf(cause, "unknown address type: %d", buf[3]);
		return (-1);
	}
	if (io_wait(io, len, timeout, cause) != 0)
		return (-1);
	io_read2(io, buf, len);

	return (0);
}
Esempio n. 27
0
boolean iscurrentportprintport (void) {
	
	return (isprintingactive () && (currentprintport == getport()));
	} /*iscurrentportprintport*/
Esempio n. 28
0
int main(int argc, char **argv)
{
	char *p;
	int c;
	const char *radius_dir = RADDBDIR;
	char filesecret[256];
	FILE *fp;
	int do_summary = 0;
	int persec = 0;
	int parallel = 1;
	radclient_t	*this;
	int force_af = AF_UNSPEC;

	fr_debug_flag = 0;

	filename_tree = rbtree_create(filename_cmp, NULL, 0);
	if (!filename_tree) {
		fprintf(stderr, "radclient: Out of memory\n");
		exit(1);
	}

	while ((c = getopt(argc, argv, "46c:d:f:Fhi:n:p:qr:sS:t:vx"
#ifdef WITH_TCP
			   "P:"
#endif
			   )) != EOF) switch(c) {
		case '4':
			force_af = AF_INET;
			break;
		case '6':
			force_af = AF_INET6;
			break;
		case 'c':
			if (!isdigit((int) *optarg))
				usage();
			resend_count = atoi(optarg);
			break;
		case 'd':
			radius_dir = optarg;
			break;
		case 'f':
			rbtree_insert(filename_tree, optarg);
			break;
		case 'F':
			print_filename = 1;
			break;
		case 'i':	/* currently broken */
			if (!isdigit((int) *optarg))
				usage();
			last_used_id = atoi(optarg);
			if ((last_used_id < 0) || (last_used_id > 255)) {
				usage();
			}
			break;

		case 'n':
			persec = atoi(optarg);
			if (persec <= 0) usage();
			break;

			/*
			 *	Note that sending MANY requests in
			 *	parallel can over-run the kernel
			 *	queues, and Linux will happily discard
			 *	packets.  So even if the server responds,
			 *	the client may not see the response.
			 */
		case 'p':
			parallel = atoi(optarg);
			if (parallel <= 0) usage();
			break;

#ifdef WITH_TCP
		case 'P':
			proto = optarg;
			if (strcmp(proto, "tcp") != 0) {
				if (strcmp(proto, "udp") == 0) {
					proto = NULL;
				} else {
					usage();
				}
			} else {
				ipproto = IPPROTO_TCP;
			}
			break;

#endif

		case 'q':
			do_output = 0;
			fr_log_fp = NULL; /* no output from you, either! */
			break;
		case 'r':
			if (!isdigit((int) *optarg))
				usage();
			retries = atoi(optarg);
			if ((retries == 0) || (retries > 1000)) usage();
			break;
		case 's':
			do_summary = 1;
			break;
               case 'S':
		       fp = fopen(optarg, "r");
                       if (!fp) {
                               fprintf(stderr, "radclient: Error opening %s: %s\n",
                                       optarg, strerror(errno));
                               exit(1);
                       }
                       if (fgets(filesecret, sizeof(filesecret), fp) == NULL) {
                               fprintf(stderr, "radclient: Error reading %s: %s\n",
                                       optarg, strerror(errno));
                               exit(1);
                       }
		       fclose(fp);

                       /* truncate newline */
		       p = filesecret + strlen(filesecret) - 1;
		       while ((p >= filesecret) &&
			      (*p < ' ')) {
			       *p = '\0';
			       --p;
		       }

                       if (strlen(filesecret) < 2) {
                               fprintf(stderr, "radclient: Secret in %s is too short\n", optarg);
                               exit(1);
                       }
                       secret = filesecret;
		       break;
		case 't':
			if (!isdigit((int) *optarg))
				usage();
			timeout = atof(optarg);
			break;
		case 'v':
			printf("%s", radclient_version);
			exit(0);
			break;
		case 'x':
			fr_debug_flag++;
			fr_log_fp = stdout;
			break;
		case 'h':
		default:
			usage();
			break;
	}
	argc -= (optind - 1);
	argv += (optind - 1);

	if ((argc < 3)  ||
	    ((secret == NULL) && (argc < 4))) {
		usage();
	}

	if (dict_init(radius_dir, RADIUS_DICTIONARY) < 0) {
		fr_perror("radclient");
		return 1;
	}

	/*
	 *	Resolve hostname.
	 */
	if (force_af == AF_UNSPEC) force_af = AF_INET;
	server_ipaddr.af = force_af;
	if (strcmp(argv[1], "-") != 0) {
		const char *hostname = argv[1];
		const char *portname = argv[1];
		char buffer[256];

		if (*argv[1] == '[') { /* IPv6 URL encoded */
			p = strchr(argv[1], ']');
			if ((size_t) (p - argv[1]) >= sizeof(buffer)) {
				usage();
			}

			memcpy(buffer, argv[1] + 1, p - argv[1] - 1);
			buffer[p - argv[1] - 1] = '\0';

			hostname = buffer;
			portname = p + 1;

		}
		p = strchr(portname, ':');
		if (p && (strchr(p + 1, ':') == NULL)) {
			*p = '\0';
			portname = p + 1;
		} else {
			portname = NULL;
		}

		if (ip_hton(hostname, force_af, &server_ipaddr) < 0) {
			fprintf(stderr, "radclient: Failed to find IP address for host %s: %s\n", hostname, strerror(errno));
			exit(1);
		}

		/*
		 *	Strip port from hostname if needed.
		 */
		if (portname) server_port = atoi(portname);
	}

	/*
	 *	See what kind of request we want to send.
	 */
	if (strcmp(argv[2], "auth") == 0) {
		if (server_port == 0) server_port = getport("radius");
		if (server_port == 0) server_port = PW_AUTH_UDP_PORT;
		packet_code = PW_AUTHENTICATION_REQUEST;

	} else if (strcmp(argv[2], "challenge") == 0) {
		if (server_port == 0) server_port = getport("radius");
		if (server_port == 0) server_port = PW_AUTH_UDP_PORT;
		packet_code = PW_ACCESS_CHALLENGE;

	} else if (strcmp(argv[2], "acct") == 0) {
		if (server_port == 0) server_port = getport("radacct");
		if (server_port == 0) server_port = PW_ACCT_UDP_PORT;
		packet_code = PW_ACCOUNTING_REQUEST;
		do_summary = 0;

	} else if (strcmp(argv[2], "status") == 0) {
		if (server_port == 0) server_port = getport("radius");
		if (server_port == 0) server_port = PW_AUTH_UDP_PORT;
		packet_code = PW_STATUS_SERVER;

	} else if (strcmp(argv[2], "disconnect") == 0) {
		if (server_port == 0) server_port = PW_COA_UDP_PORT;
		packet_code = PW_DISCONNECT_REQUEST;

	} else if (strcmp(argv[2], "coa") == 0) {
		if (server_port == 0) server_port = PW_COA_UDP_PORT;
		packet_code = PW_COA_REQUEST;

	} else if (strcmp(argv[2], "auto") == 0) {
		packet_code = -1;

	} else if (isdigit((int) argv[2][0])) {
		if (server_port == 0) server_port = getport("radius");
		if (server_port == 0) server_port = PW_AUTH_UDP_PORT;
		packet_code = atoi(argv[2]);
	} else {
		usage();
	}

	/*
	 *	Add the secret.
	 */
	if (argv[3]) secret = argv[3];

	/*
	 *	If no '-f' is specified, we're reading from stdin.
	 */
	if (rbtree_num_elements(filename_tree) == 0) {
		if (!radclient_init("-")) exit(1);
	}

	/*
	 *	Walk over the list of filenames, creating the requests.
	 */
	if (rbtree_walk(filename_tree, InOrder, filename_walk, NULL) != 0) {
		exit(1);
	}

	/*
	 *	No packets read.  Die.
	 */
	if (!radclient_head) {
		fprintf(stderr, "radclient: Nothing to send.\n");
		exit(1);
	}

	/*
	 *	Bind to the first specified IP address and port.
	 *	This means we ignore later ones.
	 */
	if (radclient_head->request->src_ipaddr.af == AF_UNSPEC) {
		memset(&client_ipaddr, 0, sizeof(client_ipaddr));
		client_ipaddr.af = server_ipaddr.af;
		client_port = 0;
	} else {
		client_ipaddr = radclient_head->request->src_ipaddr;
		client_port = radclient_head->request->src_port;
	}
#ifdef WITH_TCP
	if (proto) {
		sockfd = fr_tcp_client_socket(NULL, &server_ipaddr, server_port);
	} else
#endif
	sockfd = fr_socket(&client_ipaddr, client_port);
	if (sockfd < 0) {
		fprintf(stderr, "radclient: socket: %s\n", fr_strerror());
		exit(1);
	}

	pl = fr_packet_list_create(1);
	if (!pl) {
		fprintf(stderr, "radclient: Out of memory\n");
		exit(1);
	}

	if (!fr_packet_list_socket_add(pl, sockfd, ipproto, &server_ipaddr,
				       server_port, NULL)) {
		fprintf(stderr, "radclient: Out of memory\n");
		exit(1);
	}

	/*
	 *	Walk over the list of packets, sanity checking
	 *	everything.
	 */
	for (this = radclient_head; this != NULL; this = this->next) {
		this->request->src_ipaddr = client_ipaddr;
		this->request->src_port = client_port;
		if (radclient_sane(this) != 0) {
			exit(1);
		}
	}

	/*
	 *	Walk over the packets to send, until
	 *	we're all done.
	 *
	 *	FIXME: This currently busy-loops until it receives
	 *	all of the packets.  It should really have some sort of
	 *	send packet, get time to wait, select for time, etc.
	 *	loop.
	 */
	do {
		int n = parallel;
		radclient_t *next;
		const char *filename = NULL;

		done = 1;
		sleep_time = -1;

		/*
		 *	Walk over the packets, sending them.
		 */

		for (this = radclient_head; this != NULL; this = next) {
			next = this->next;

			/*
			 *	If there's a packet to receive,
			 *	receive it, but don't wait for a
			 *	packet.
			 */
			recv_one_packet(0);

			/*
			 *	This packet is done.  Delete it.
			 */
			if (this->done) {
				radclient_free(this);
				continue;
			}

			/*
			 *	Packets from multiple '-f' are sent
			 *	in parallel.
			 *
			 *	Packets from one file are sent in
			 *	series, unless '-p' is specified, in
			 *	which case N packets from each file
			 *	are sent in parallel.
			 */
			if (this->filename != filename) {
				filename = this->filename;
				n = parallel;
			}

			if (n > 0) {
				n--;

				/*
				 *	Send the current packet.
				 */
				send_one_packet(this);

				/*
				 *	Wait a little before sending
				 *	the next packet, if told to.
				 */
				if (persec) {
					struct timeval tv;

					/*
					 *	Don't sleep elsewhere.
					 */
					sleep_time = 0;

					if (persec == 1) {
						tv.tv_sec = 1;
						tv.tv_usec = 0;
					} else {
						tv.tv_sec = 0;
						tv.tv_usec = 1000000/persec;
					}

					/*
					 *	Sleep for milliseconds,
					 *	portably.
					 *
					 *	If we get an error or
					 *	a signal, treat it like
					 *	a normal timeout.
					 */
					select(0, NULL, NULL, NULL, &tv);
				}

				/*
				 *	If we haven't sent this packet
				 *	often enough, we're not done,
				 *	and we shouldn't sleep.
				 */
				if (this->resend < resend_count) {
					done = 0;
					sleep_time = 0;
				}
			} else { /* haven't sent this packet, we're not done */
				assert(this->done == 0);
				assert(this->reply == NULL);
				done = 0;
			}
		}

		/*
		 *	Still have outstanding requests.
		 */
		if (fr_packet_list_num_elements(pl) > 0) {
			done = 0;
		} else {
			sleep_time = 0;
		}

		/*
		 *	Nothing to do until we receive a request, so
		 *	sleep until then.  Once we receive one packet,
		 *	we go back, and walk through the whole list again,
		 *	sending more packets (if necessary), and updating
		 *	the sleep time.
		 */
		if (!done && (sleep_time > 0)) {
			recv_one_packet(sleep_time);
		}
	} while (!done);

	rbtree_free(filename_tree);
	fr_packet_list_free(pl);
	while (radclient_head) radclient_free(radclient_head);
	dict_free();

	if (do_summary) {
		printf("\n\t   Total approved auths:  %d\n", totalapp);
		printf("\t     Total denied auths:  %d\n", totaldeny);
		printf("\t       Total lost auths:  %d\n", totallost);
	}

	if (success) return 0;

	return 1;
}
Esempio n. 29
0
void
pip(char *net, Dir *db)
{
	int n, fd;
	char buf[128], *p;
	char *dname;

	if(strcmp(db->name, "clone") == 0)
		return;
	if(strcmp(db->name, "stats") == 0)
		return;

	snprint(buf, sizeof buf, "%s/%s/%s/status", netroot, net, db->name);
	fd = open(buf, OREAD);
	if(fd < 0)
		return;
	n = read(fd, buf, sizeof(buf));
	close(fd);
	if(n < 0)
		return;
	buf[n] = 0;

	p = strchr(buf, ' ');
	if(p != 0)
		*p = 0;
	p = strrchr(buf, '\n');
	if(p != 0)
		*p = 0;
	Bprint(&out, "%-4s %-4s %-10s %-12s ", net, db->name, db->uid, buf);

	snprint(buf, sizeof buf, "%s/%s/%s/local", netroot, net, db->name);
	fd = open(buf, OREAD);
	if(fd < 0) {
		Bprint(&out, "\n");
		return;
	}
	n = read(fd, buf, sizeof(buf));
	close(fd);
	if(n < 0) {
		Bprint(&out, "\n");
		return;
	}
	buf[n-1] = 0;
	p = strchr(buf, '!');
	if(p == 0) {
		Bprint(&out, "\n");
		return;
	}
	*p = '\0';
	Bprint(&out, "%-10s ", getport(net, p+1));

	snprint(buf, sizeof buf, "%s/%s/%s/remote", netroot, net, db->name);
	fd = open(buf, OREAD);
	if(fd < 0) {
		print("\n");
		return;
	}
	n = read(fd, buf, sizeof(buf));
	close(fd);
	if(n < 0) {
		print("\n");
		return;
	}
	buf[n-1] = 0;
	p = strchr(buf, '!');
	if(p != nil)
		*p++ = '\0';

	if(notrans){
		Bprint(&out, "%-10s %s\n", getport(net, p), buf);
		return;
	}
	dname = csgetvalue(netroot, "ip", buf, "dom", nil);
	if(dname == nil) {
		Bprint(&out, "%-10s %s\n", getport(net, p), buf);
		return;
	}
	Bprint(&out, "%-10s %s\n", getport(net, p), dname);
	Bflush(&out);
	free(dname);
}
Esempio n. 30
0
int main(int argc, char **argv)
{
	RADIUS_PACKET *req;
	char *p;
	int c;
	uint16_t port = 0;
	char *filename = NULL;
	FILE *fp;
	int id;
	int force_af = AF_UNSPEC;

	static fr_log_t radclient_log = {
		.colourise = true,
		.fd = STDOUT_FILENO,
		.dst = L_DST_STDOUT,
		.file = NULL,
		.debug_file = NULL,
	};

	radlog_init(&radclient_log, false);

	/*
	 *	We probably don't want to free the talloc autofree context
	 *	directly, so we'll allocate a new context beneath it, and
	 *	free that before any leak reports.
	 */
	TALLOC_CTX *autofree = talloc_init("main");

	id = ((int)getpid() & 0xff);
	fr_debug_flag = 0;

	set_radius_dir(autofree, RADIUS_DIR);

	while ((c = getopt(argc, argv, "46c:d:D:f:hi:qst:r:S:xXv")) != EOF)
	{
		switch(c) {
		case '4':
			force_af = AF_INET;
			break;
		case '6':
			force_af = AF_INET6;
			break;
		case 'd':
			set_radius_dir(autofree, optarg);
			break;
		case 'D':
			main_config.dictionary_dir = talloc_typed_strdup(NULL, optarg);
			break;
		case 'f':
			filename = optarg;
			break;
		case 'q':
			do_output = 0;
			break;
		case 'x':
			debug_flag++;
			fr_debug_flag++;
			break;

		case 'X':
#if 0
		  sha1_data_problems = 1; /* for debugging only */
#endif
		  break;



		case 'r':
			if (!isdigit((int) *optarg))
				usage();
			retries = atoi(optarg);
			break;
		case 'i':
			if (!isdigit((int) *optarg))
				usage();
			id = atoi(optarg);
			if ((id < 0) || (id > 255)) {
				usage();
			}
			break;
		case 's':
			do_summary = 1;
			break;
		case 't':
			if (!isdigit((int) *optarg))
				usage();
			timeout = atof(optarg);
			break;
		case 'v':
			printf("radeapclient: $Id: 69643e042c5a7c9053977756a5623e3c07598f2e $ built on " __DATE__ " at " __TIME__ "\n");
			exit(0);
			break;
	       case 'S':
		       fp = fopen(optarg, "r");
		       if (!fp) {
			       fprintf(stderr, "radclient: Error opening %s: %s\n",
				       optarg, fr_syserror(errno));
			       exit(1);
		       }
		       if (fgets(filesecret, sizeof(filesecret), fp) == NULL) {
			       fprintf(stderr, "radclient: Error reading %s: %s\n",
				       optarg, fr_syserror(errno));
			       exit(1);
		       }
		       fclose(fp);

		       /* truncate newline */
		       p = filesecret + strlen(filesecret) - 1;
		       while ((p >= filesecret) &&
			      (*p < ' ')) {
			       *p = '\0';
			       --p;
		       }

		       if (strlen(filesecret) < 2) {
			       fprintf(stderr, "radclient: Secret in %s is too short\n", optarg);
			       exit(1);
		       }
		       secret = filesecret;
		       break;
		case 'h':
		default:
			usage();
			break;
		}
	}
	argc -= (optind - 1);
	argv += (optind - 1);

	if ((argc < 3)  ||
	    ((!secret) && (argc < 4))) {
		usage();
	}

	if (!main_config.dictionary_dir) {
		main_config.dictionary_dir = DICTDIR;
	}

	/*
	 *	Read the distribution dictionaries first, then
	 *	the ones in raddb.
	 */
	DEBUG2("including dictionary file %s/%s", main_config.dictionary_dir, RADIUS_DICTIONARY);
	if (dict_init(main_config.dictionary_dir, RADIUS_DICTIONARY) != 0) {
		ERROR("Errors reading dictionary: %s",
		      fr_strerror());
		exit(1);
	}

	/*
	 *	It's OK if this one doesn't exist.
	 */
	int rcode = dict_read(radius_dir, RADIUS_DICTIONARY);
	if (rcode == -1) {
		ERROR("Errors reading %s/%s: %s", radius_dir, RADIUS_DICTIONARY,
		      fr_strerror());
		exit(1);
	}

	/*
	 *	We print this after reading it.  That way if
	 *	it doesn't exist, it's OK, and we don't print
	 *	anything.
	 */
	if (rcode == 0) {
		DEBUG2("including dictionary file %s/%s", radius_dir, RADIUS_DICTIONARY);
	}

	req = rad_alloc(NULL, 1);
	if (!req) {
		fr_perror("radclient");
		exit(1);
	}

#if 0
	{
		FILE *randinit;

		if((randinit = fopen("/dev/urandom", "r")) == NULL)
		{
			perror("/dev/urandom");
		} else {
			fread(randctx.randrsl, 256, 1, randinit);
			fclose(randinit);
		}
	}
	fr_randinit(&randctx, 1);
#endif

	req->id = id;

	/*
	 *	Resolve hostname.
	 */
	if (force_af == AF_UNSPEC) force_af = AF_INET;
	req->dst_ipaddr.af = force_af;
	if (strcmp(argv[1], "-") != 0) {
		char const *hostname = argv[1];
		char const *portname = argv[1];
		char buffer[256];

		if (*argv[1] == '[') { /* IPv6 URL encoded */
			p = strchr(argv[1], ']');
			if ((size_t) (p - argv[1]) >= sizeof(buffer)) {
				usage();
			}

			memcpy(buffer, argv[1] + 1, p - argv[1] - 1);
			buffer[p - argv[1] - 1] = '\0';

			hostname = buffer;
			portname = p + 1;

		}
		p = strchr(portname, ':');
		if (p && (strchr(p + 1, ':') == NULL)) {
			*p = '\0';
			portname = p + 1;
		} else {
			portname = NULL;
		}

		if (ip_hton(&req->dst_ipaddr, force_af, hostname, false) < 0) {
			fprintf(stderr, "radclient: Failed to find IP address for host %s: %s\n", hostname, fr_syserror(errno));
			exit(1);
		}

		/*
		 *	Strip port from hostname if needed.
		 */
		if (portname) port = atoi(portname);
	}

	/*
	 *	See what kind of request we want to send.
	 */
	if (strcmp(argv[2], "auth") == 0) {
		if (port == 0) port = getport("radius");
		if (port == 0) port = PW_AUTH_UDP_PORT;
		req->code = PW_CODE_AUTHENTICATION_REQUEST;

	} else if (strcmp(argv[2], "acct") == 0) {
		if (port == 0) port = getport("radacct");
		if (port == 0) port = PW_ACCT_UDP_PORT;
		req->code = PW_CODE_ACCOUNTING_REQUEST;
		do_summary = 0;

	} else if (strcmp(argv[2], "status") == 0) {
		if (port == 0) port = getport("radius");
		if (port == 0) port = PW_AUTH_UDP_PORT;
		req->code = PW_CODE_STATUS_SERVER;

	} else if (strcmp(argv[2], "disconnect") == 0) {
		if (port == 0) port = PW_POD_UDP_PORT;
		req->code = PW_CODE_DISCONNECT_REQUEST;

	} else if (isdigit((int) argv[2][0])) {
		if (port == 0) port = getport("radius");
		if (port == 0) port = PW_AUTH_UDP_PORT;
		req->code = atoi(argv[2]);
	} else {
		usage();
	}
	req->dst_port = port;

	/*
	 *	Add the secret.
	 */
	if (argv[3]) secret = argv[3];

	/*
	 *	Read valuepairs.
	 *	Maybe read them, from stdin, if there's no
	 *	filename, or if the filename is '-'.
	 */
	if (filename && (strcmp(filename, "-") != 0)) {
		fp = fopen(filename, "r");
		if (!fp) {
			fprintf(stderr, "radclient: Error opening %s: %s\n",
				filename, fr_syserror(errno));
			exit(1);
		}
	} else {
		fp = stdin;
	}

	/*
	 *	Send request.
	 */
	if ((req->sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
		perror("radclient: socket: ");
		exit(1);
	}

	while(!filedone) {
		if (req->vps) pairfree(&req->vps);
		if (readvp2(&req->vps, NULL, fp, &filedone) < 0) {
			fr_perror("radeapclient");
			break;
		}

		sendrecv_eap(req);
	}

	if(do_summary) {
		printf("\n\t   Total approved auths:  %d\n", totalapp);
		printf("\t     Total denied auths:  %d\n", totaldeny);
	}

	talloc_free(autofree);

	return 0;
}

/*
 * given a radius request with some attributes in the EAP range, build
 * them all into a single EAP-Message body.
 *
 * Note that this function will build multiple EAP-Message bodies
 * if there are multiple eligible EAP-types. This is incorrect, as the
 * recipient will in fact concatenate them.
 *
 * XXX - we could break the loop once we process one type. Maybe this
 *       just deserves an assert?
 *
 */
static void map_eap_methods(RADIUS_PACKET *req)
{
	VALUE_PAIR *vp, *vpnext;
	int id, eapcode;
	int eap_method;

	eap_packet_t *pt_ep = talloc_zero(req, eap_packet_t);

	vp = pairfind(req->vps, ATTRIBUTE_EAP_ID, 0, TAG_ANY);
	if(!vp) {
		id = ((int)getpid() & 0xff);
	} else {
		id = vp->vp_integer;
	}

	vp = pairfind(req->vps, ATTRIBUTE_EAP_CODE, 0, TAG_ANY);
	if(!vp) {
		eapcode = PW_EAP_REQUEST;
	} else {
		eapcode = vp->vp_integer;
	}

	for(vp = req->vps; vp != NULL; vp = vpnext) {
		/* save it in case it changes! */
		vpnext = vp->next;

		if(vp->da->attr >= ATTRIBUTE_EAP_BASE &&
		   vp->da->attr < ATTRIBUTE_EAP_BASE+256) {
			break;
		}
	}

	if(!vp) {
		return;
	}

	eap_method = vp->da->attr - ATTRIBUTE_EAP_BASE;

	switch(eap_method) {
	case PW_EAP_IDENTITY:
	case PW_EAP_NOTIFICATION:
	case PW_EAP_NAK:
	case PW_EAP_MD5:
	case PW_EAP_OTP:
	case PW_EAP_GTC:
	case PW_EAP_TLS:
	case PW_EAP_LEAP:
	case PW_EAP_TTLS:
	case PW_EAP_PEAP:
	default:
		/*
		 * no known special handling, it is just encoded as an
		 * EAP-message with the given type.
		 */

		/* nuke any existing EAP-Messages */
		pairdelete(&req->vps, PW_EAP_MESSAGE, 0, TAG_ANY);

		pt_ep->code = eapcode;
		pt_ep->id = id;
		pt_ep->type.num = eap_method;
		pt_ep->type.length = vp->length;

		pt_ep->type.data = talloc_memdup(vp, vp->vp_octets, vp->length);
		talloc_set_type(pt_ep->type.data, uint8_t);

		eap_basic_compose(req, pt_ep);
	}
}