C_RESULT vp_com_wf_disconnect(vp_com_wifi_config_t* config, vp_com_wifi_connection_t* connection)
{
  C_RESULT res = VP_COM_OK;
#ifdef USE_IWLIB
  struct iwreq wrq;
  char essid[IW_ESSID_MAX_SIZE + 1];

  int wlsock = iw_sockets_open();

  vp_os_memset(&wrq, 0, sizeof(struct iwreq));

  strncpy(essid, connection->networkName, strlen(connection->networkName));
  wrq.u.essid.flags = 0;
  wrq.u.essid.pointer = (caddr_t) essid;
  wrq.u.essid.length = strlen(essid);
  if(iw_get_kernel_we_version() < 21)
    wrq.u.essid.length++; // Get version from kernel, device may not have range...

  res = ( iw_set_ext( wlsock, config->itfName, SIOCSIWESSID, &wrq) < 0 ) ? VP_COM_ERROR : VP_COM_OK;

  iw_sockets_close(wlsock);
#endif

  return res;
}
Example #2
0
int change_channel(int channel)
{
        int skfd = 0, ret_val = 0;
        struct iwreq wrq;

        memset((void *) &wrq, 0, sizeof(struct iwreq));

        /* Open NET socket */
        if((skfd = iw_sockets_open()) < 0)
        {
                perror("iw_sockets_open");
        }
        else if(get_iface())
        {
                /* Convert channel to a frequency */
                iw_float2freq((double) channel, &(wrq.u.freq));

                /* Fixed frequency */
                wrq.u.freq.flags = IW_FREQ_FIXED;

        	cprintf(VERBOSE, "[+] Switching %s to channel %d\n", get_iface(), channel);

                /* Set frequency */
                if(iw_set_ext(skfd, get_iface(), SIOCSIWFREQ, &wrq) >= 0)
                {
			set_channel(channel);
                        ret_val = 1;
                }

                iw_sockets_close(skfd);
        }

        return ret_val;
}
Example #3
0
/*
 * The main !
 */
int
iwpriv_main(int	argc,
     char **	argv)
{
  int skfd, i;		/* generic raw socket desc.	*/
  int goterr = 0;

  /* Create a channel to the NET kernel. */
  if((skfd = iw_sockets_open()) < 0)
    {
      perror("socket");
      return(-1);
    }

  /* No argument : show the list of all devices + ioctl list */
  if(argc == 1)
    iw_enum_devices(skfd, &print_priv_info, NULL, 0);
  else
    /* Special cases take one... */
    /* All */
    if((!strncmp(argv[1], "-a", 2)) || (!strcmp(argv[1], "--all")))
      iw_enum_devices(skfd, &print_priv_all, NULL, 0);
    else
      /* Help */
      if((!strncmp(argv[1], "-h", 2)) || (!strcmp(argv[1], "--help")))
	iw_usage();
      else
	/* Version */
	if (!strcmp(argv[1], "-v") || !strcmp(argv[1], "--version"))
	  goterr = iw_print_version_info("iwpriv");
	else
	  /* The device name must be the first argument */
	  /* Name only : show for that device only */
	  if(argc == 2)
	    print_priv_info(skfd, argv[1], NULL, 0);
	  else
	    /* Special cases take two... */
	    /* All */
	    if((!strncmp(argv[2], "-a", 2)) ||
	       (!strcmp(argv[2], "--all")))
	      print_priv_all(skfd, argv[1], NULL, 0);
	    else
	      /* Roaming */
	      if(!strncmp(argv[2], "roam", 4))
		goterr = set_roaming(skfd, argv + 3, argc - 3, argv[1]);
	      else
		/* Port type */
		if(!strncmp(argv[2], "port", 4))
		  goterr = port_type(skfd, argv + 3, argc - 3, argv[1]);
		else
		  /*-------------*/
		  /* Otherwise, it's a private ioctl */
		  goterr = set_private(skfd, argv + 2, argc - 2, argv[1]);

  /* Close the socket. */
  iw_sockets_close(skfd);

  return(goterr);
}
Example #4
0
/* ------------------------------------------------------------------- WirelessInterface_dealloc */
static void WirelessInterface_dealloc(wiface* self)
{
	if (self->ifname)
		free(self->ifname);

	iw_sockets_close(self->sock);
	self->ob_type->tp_free((PyObject*)(self));
}
Example #5
0
	void CWextHW::close() {
		m_sqTimer.stop();
		m_scTimer.stop();
		if (-1 != m_wextFd) {
			iw_sockets_close(m_wextFd);
			m_wextFd = -1;
		}
	}
Example #6
0
/*
 * Get interface data from cache or live interface
 */
static struct wireless_iface *
iw_get_interface_data(int	ifindex)
{
  struct wireless_iface *	curr;
  int				skfd = -1;	/* ioctl socket */

  /* Search for it in the database */
  curr = interface_cache;
  while(curr != NULL)
    {
      /* Match ? */
      if(curr->ifindex == ifindex)
	{
	  //printf("Cache : found %d-%s\n", curr->ifindex, curr->ifname);

	  /* Return */
	  return(curr);
	}
      /* Next entry */
      curr = curr->next;
    }

  /* Create a channel to the NET kernel. Doesn't happen too often, so
   * socket creation overhead is minimal... */
  if((skfd = iw_sockets_open()) < 0)
    {
      perror("iw_sockets_open");
      return(NULL);
    }

  /* Create new entry, zero, init */
  curr = calloc(1, sizeof(struct wireless_iface));
  if(!curr)
    {
      fprintf(stderr, "Malloc failed\n");
      return(NULL);
    }
  curr->ifindex = ifindex;

  /* Extract static data */
  if(index2name(skfd, ifindex, curr->ifname) < 0)
    {
      perror("index2name");
      free(curr);
      return(NULL);
    }
  curr->has_range = (iw_get_range_info(skfd, curr->ifname, &curr->range) >= 0);
  //printf("Cache : create %d-%s\n", curr->ifindex, curr->ifname);

  /* Done */
  iw_sockets_close(skfd);

  /* Link it */
  curr->next = interface_cache;
  interface_cache = curr;

  return(curr);
}
C_RESULT vp_com_wf_get_rssi(vp_com_wifi_config_t* cfg, int32_t* rssi)
{
#ifdef USE_IWLIB
  struct iwreq wrq;
  iwstats stats;
  iwrange range;

  int wlsock = iw_sockets_open();

  vp_os_memset(&wrq, 0, sizeof(struct iwreq));
  iw_get_stats(wlsock, cfg->itfName, &stats, &range, 1);
  iw_sockets_close(wlsock);

//   struct  iw_statistics
//   {
//     __u16           status;           // Status * - device dependent for now
//     struct iw_quality       qual;     // Quality of the link * (instant/mean/max)
//     struct iw_discarded     discard;  // Packet discarded counts
//     struct iw_missed        miss;     // Packet missed counts
//   };
//
//   struct iw_range
//   {
//     ...
//     //  Quality of link & SNR stuff */
//     //  Quality range (link, level, noise)
//     //  If the quality is absolute, it will be in the range [0 ; max_qual],
//     //  if the quality is dBm, it will be in the range [max_qual ; 0].
//     //  Don't forget that we use 8 bit arithmetics...
//     struct iw_quality       max_qual;       // Quality of the link
//     //  This should contain the average/typical values of the quality
//     //  indicator. This should be the threshold between a "good" and
//     //  a "bad" link (example : monitor going from green to orange).
//     //  Currently, user space apps like quality monitors don't have any
//     //  way to calibrate the measurement. With this, they can split
//     //  the range between 0 and max_qual in different quality level
//     //  (using a geometric subdivision centered on the average).
//     //  I expect that people doing the user space apps will feedback
//     //  us on which value we need to put in each driver...
//     struct iw_quality       avg_qual;       // Quality of the link
//     ...
//   };
//   struct  iw_quality
//   {
//     __u8            qual;           // link quality (%retries, SNR, %missed beacons or better...)
//     __u8            level;          // signal level (dBm)
//     __u8            noise;          // noise level (dBm)
//     __u8            updated;        // Flags to know if updated
//   };

  *rssi = stats.qual.qual;

#endif
  return VP_COM_OK;
}
Example #8
0
int connect_wifi()
{
  struct iwreq wrq;
  char essid[IW_ESSID_MAX_SIZE + 1];
  unsigned char key[IW_ENCODING_TOKEN_MAX];
  int32_t keylen = 0;

  int wlsock = iw_sockets_open();

  const char *itfName = "wlan0";
  const char *networkName = "linksys";
  const char *com_key = "9F1C3EE11CBA230B27BF1C1B6F";
  if(wlsock < 0)
    return -1;

  memset(&wrq,0,sizeof(struct iwreq));

  keylen = iw_in_key_full(wlsock, itfName, com_key, key, &wrq.u.data.flags);
  if(keylen <= 0)
    return -1;

  wrq.u.data.length   = keylen;
  wrq.u.data.pointer  = (caddr_t) key;
  wrq.u.data.flags |= IW_ENCODE_RESTRICTED;

  if(iw_set_ext(wlsock, itfName, SIOCSIWENCODE, &wrq) < 0)
    return -1;

  memset(&wrq,0,sizeof(struct iwreq));

  wrq.u.mode = IW_MODE_INFRA;

  if(iw_set_ext( wlsock, itfName, SIOCSIWMODE, &wrq) < 0)
    return -1;

  if(strlen(networkName) > IW_ESSID_MAX_SIZE)
    return -1;

  memset(essid,0,IW_ESSID_MAX_SIZE + 1);
  memset(&wrq,0,sizeof(struct iwreq));

  strncpy(essid,networkName,strlen(networkName));
  wrq.u.essid.flags = 1;
  wrq.u.essid.pointer = (caddr_t) essid;
  wrq.u.essid.length = strlen(essid) + 1;

  if(iw_set_ext( wlsock, itfName, SIOCSIWESSID, &wrq) < 0)
    return -1;

  iw_sockets_close(wlsock);

  return 0;

}
Example #9
0
int get_essid(char *name, int *channel)
{
	int sockfd;
	char essid[16];
	struct iwreq wrq;
	int ioc;

	sockfd = iw_sockets_open();
	double freq;
	struct iw_range *range;
	char buffer[sizeof(iwrange) * 2];

	memset(essid, '\0', sizeof(essid));

	/* After IOCTL call the result will be stored in iwreq
	 * structure. Hence prepare the structure to hold the
	 * results.
	 */
	wrq.u.essid.pointer = (caddr_t) essid;
	wrq.u.essid.length = IW_ESSID_MAX_SIZE + 2;
	wrq.u.essid.flags = 0;
	ioc = get_param(sockfd, SIOCGIWESSID, ifname_config, &wrq);
	strcpy(name, wrq.u.essid.pointer);	/* Obtain the essid pointed by the pointer */

	/* Prepare the structure to get wireless range info */

	bzero(buffer, sizeof(buffer));
	wrq.u.data.pointer = (caddr_t) buffer;
	wrq.u.data.length = sizeof(buffer);
	wrq.u.data.flags = 0;
	if (get_param(sockfd, SIOCGIWRANGE, ifname_config, &wrq) < 0) {
		syslog(LOG_ERR, "ERROR:%s: %s\n", ifname_config,
		       strerror(errno));
		return -1;
	}

	/* Obtain the frequency the current network is operating in */
	range = (struct iw_range *)buffer;
	ioc = get_param(sockfd, SIOCGIWFREQ, ifname_config, &wrq);
	if (ioc == -1) {
		syslog(LOG_ERR, "ERROR:%s: %s\n", ifname_config,
		       strerror(errno));
	}

	/* Convert the frequency into channel no */
	freq = iw_freq2float(&(wrq.u.freq));
	*channel = iw_freq_to_channel(freq, range);
	iw_sockets_close(sockfd);
	return 1;
}
Example #10
0
static int iwscan_ifname_hasiwname(char* ifname)
{
	int ret = 0;
	int skfd;
	iwreq wrq;

	if ((skfd = iw_sockets_open()) >= 0) {
		if (iw_get_ext(skfd, ifname, SIOCGIWNAME, &wrq) >= 0)
			ret++;

		iw_sockets_close(skfd);
	}

	return ret;
}
Example #11
0
/*
 * The main !
 */
int
main(int	argc,
     char **	argv)
{
  int skfd;		/* generic raw socket desc.	*/
  int goterr = 0;

  /* Create a channel to the NET kernel. */
  if((skfd = iw_sockets_open()) < 0)
    {
      perror("socket");
      exit(-1);
    }

  /* No argument : show the list of all device + info */
  if(argc == 1)
    iw_enum_devices(skfd, &print_info, NULL, 0);
  else
    /* Special case for help... */
    if((!strcmp(argv[1], "-h")) || (!strcmp(argv[1], "--help")))
      iw_usage();
    else
      /* Special case for version... */
      if(!strcmp(argv[1], "-v") || !strcmp(argv[1], "--version"))
	goterr = iw_print_version_info("iwconfig");
      else
	{
	  /* '--' escape device name */
	  if((argc > 2) && !strcmp(argv[1], "--"))
	    {
	      argv++;
	      argc--;
	    }

	  /* The device name must be the first argument */
	  if(argc == 2)
	    print_info(skfd, argv[1], NULL, 0);
	  else
	    /* The other args on the line specify options to be set... */
	    goterr = set_info(skfd, argv + 2, argc - 2, argv[1]);
	}

  /* Close the socket. */
  iw_sockets_close(skfd);

  return(goterr);
}
Example #12
0
/*
 * The main !
 */
int
main(int	argc,
     char **	argv)
{
  int skfd;			/* generic raw socket desc.	*/
  int goterr = 0;

  /* Create a channel to the NET kernel. */
  if((skfd = iw_sockets_open()) < 0)
    {
      perror("socket");
      return(-1);
    }

  /* No argument : show the list of all device + info */
  if(argc == 1)
    iw_enum_devices(skfd, &print_spy_info, NULL, 0);
  else
    /* Special cases take one... */
    /* Help */
    if((!strcmp(argv[1], "-h")) || (!strcmp(argv[1], "--help")))
      fprintf(stderr, "Usage: iwspy interface [+] [MAC address] [IP address]\n");
    else
      /* Version */
      if (!strcmp(argv[1], "-v") || !strcmp(argv[1], "--version"))
	goterr = iw_print_version_info("iwspy");
      else
	/* The device name must be the first argument */
	/* Name only : show spy list for that device only */
	if(argc == 2)
	  goterr = print_spy_info(skfd, argv[1], NULL, 0);
	else
	  /* Special commands */
	  if(!strcmp(argv[2], "setthr"))
	    goterr = set_spy_threshold(skfd, argv[1], argv + 3, argc - 3);
	  else
	    if(!strcmp(argv[2], "getthr"))
	      goterr = get_spy_threshold(skfd, argv[1], argv + 3, argc - 3);
	    else
	      /* Otherwise, it's a list of address to set in the spy list */
	      goterr = set_spy_info(skfd, argv[1], argv + 2, argc - 2);

  /* Close the socket. */
  iw_sockets_close(skfd);

  return(goterr);
}
Example #13
0
wireless_scan *show_menu() {
	/* Init ncurses */
	initscr(); raw(); noecho(); curs_set(0);
	start_color(); use_default_colors();
	init_pair(1,1,-1); init_pair(2,2,-1); init_pair(3,3,-1);
	init_pair(4,4,-1); init_pair(5,5,-1); init_pair(6,6,-1);
	init_pair(7,7,-1);
	/* Select entry */
	wireless_scan *ws, *ss;
	int running = True;
	int c,i,sel = 0;
	int n = refresh_list();
	while (running) {
		move(0,0);
		attrset(COLOR_PAIR(4)|A_REVERSE|A_BOLD);
		printw(" *  %-*s  %%  \n",IW_ESSID_MAX_SIZE+2,"Network"); 
		for (ws = context.result, i=0; ws; ws = ws->next)
			if ((mode & MODE_HIDDEN) || strlen(ws->b.essid)) {
				if (i == sel) ss = ws;
				draw_entry(ws,((i++)==sel));
			}
		attrset(COLOR_PAIR(4)|A_REVERSE|A_BOLD);
		printw("  %-*s \n",IW_ESSID_MAX_SIZE+8," ");
		refresh();
		c = getchar();
		if (c == 'q') running = False;
		else if (c == 13) break;
		else if (c == 'r') n = refresh_list();
		else if (c == 'j' || c == 66) sel++;
		else if (c == 'k' || c == 65) sel--;
		if (sel >= n) sel = n;
		else if (sel < 0) sel = 0;
	}
	endwin();
	if (!running) {	/* "q" selected */
		iw_sockets_close(skfd);
		exit(0);
	}
	for (i = 0, ws = context.result; i != sel; ws = ws->next)
		if ((mode & MODE_HIDDEN) || strlen(ws->b.essid)) i++;
	/* End ncurses session & return result */
	return ws;
}
Example #14
0
int main(void) {
	Display *dpy;
	Window root;
	char status[201], net[30], vol[14], cpu[14], mem[14], bat[48];
	int netloops = 60;

	dpy = XOpenDisplay(NULL);
	if(dpy == NULL) {
		fprintf(stderr, "ERROR: could not open display\n");
		return 1;
	}
	root = XRootWindow(dpy, DefaultScreen(dpy));
	winfo = malloc(sizeof(struct wireless_info));
	memset(winfo, 0, sizeof(struct wireless_info));

	skfd = iw_sockets_open();

	infile = fopen(CPU_F, "r");
	fscanf(infile, "cpu %ld %ld %ld %ld", &jif1, &jif2, &jif3, &jif4); fclose(infile);

	while(1) {
		if(++netloops > 60) {
			netloops = 0;
			get_wifi(net);
		}
		get_vol(vol);
		get_cpu(cpu);
		get_mem(mem);
		get_bat(bat);

		sprintf(status, "%s %s %s %s %s", net, vol, cpu, mem, bat);

		XStoreName(dpy, root, status);
		XFlush(dpy);
		sleep(INTERVAL);
	}
	/* NEXT LINES SHOULD NEVER EXECUTE! */
	XCloseDisplay(dpy);
	iw_sockets_close(skfd);
	return 0;
}
C_RESULT vp_com_wf_connect(vp_com_t* vp_com, vp_com_wifi_connection_t* connection, int32_t numAttempts)
{
  C_RESULT res = VP_COM_OK;
#ifdef USE_IWLIB
  int32_t wlsock;
  vp_com_wifi_config_t* config = (vp_com_wifi_config_t*)vp_com->config;
  wireless_config iwconf;

  wlsock = iw_sockets_open();

  res = ( wlsock < 0 ) ? VP_COM_ERROR : VP_COM_OK;
  VP_COM_CHECK( res );

  iw_get_basic_config( wlsock, config->itfName, &iwconf );

  iwconf.has_nwid = 0;
  iwconf.has_freq = 0;
  iwconf.has_key  = 0;

  iwconf.has_mode = 1;
  iwconf.mode = config->infrastructure ? IW_MODE_INFRA : IW_MODE_ADHOC;

  iwconf.has_essid = 1;
  iwconf.essid_on = 1;
  strncpy( &iwconf.essid[0], connection->networkName, IW_ESSID_MAX_SIZE+1 );
  
  res = iw_set_basic_config( wlsock, config->itfName, &iwconf ) < 0 ? C_FAIL : C_OK;

  if( SUCCEED(res) )
    PRINT(" OK!\n");
  else
    PRINT(" FAILED!\n");

  iw_sockets_close(wlsock);

#endif
  return res;
}
Example #16
0
int
handle_channel(netsnmp_mib_handler *handler,
                          netsnmp_handler_registration *reginfo,
                          netsnmp_agent_request_info   *reqinfo,
                          netsnmp_request_info         *requests)
{
    int ret;
    char channel_str[255];
    int channel; 
    static int skfd;

    /* We are never called for a GETNEXT if it's registered as a
       "instance", as it's "magically" handled for us.  */

    /* a instance handler also only hands us one request at a time, so
       we don't need to loop over a list of requests; we'll only get one. */
    
    switch(reqinfo->mode) {

        case MODE_GET:
                printf("bitrate MODE_GET\n");
                if((skfd = iw_sockets_open()) < 0) {
                        channel = -4;
                }
                else {
                        channel = get_channel(skfd, INTERFACE);
                }
                sprintf(channel_str, "%d", channel);
                snmp_set_var_typed_value(requests->requestvb, ASN_OCTET_STR,
                                (u_char *) channel_str, strlen(channel_str));
                if(skfd >= 0)
                        iw_sockets_close(skfd);
                break;

        /*
         * SET REQUEST
         *
         * multiple states in the transaction.  See:
         * http://www.net-snmp.org/tutorial-5/toolkit/mib_module/set-actions.jpg
         */
        case MODE_SET_RESERVE1:
                printf("bitrate MODE_SET_RESERVE1\n");
                /* or you could use netsnmp_check_vb_type_and_size instead */
            ret = netsnmp_check_vb_type(requests->requestvb, ASN_OCTET_STR);
            if ( ret != SNMP_ERR_NOERROR ) {
                netsnmp_set_request_error(reqinfo, requests, ret );
            }
            break;

        case MODE_SET_RESERVE2:
                printf("bitrate MODE_SET_RESERVE2\n");
            /* malloc "undo" storage buffer */
	    if((skfd = iw_sockets_open()) < 0) {
                netsnmp_set_request_error(reqinfo, requests, SNMP_ERR_RESOURCEUNAVAILABLE);
            }
            break;

        case MODE_SET_FREE:
                printf("bitrate MODE_SET_FREE\n");
            /* free resources allocated in RESERVE1 and/or
               RESERVE2.  Something failed somewhere, and the states
               below won't be called. */
	    if(skfd >= 0)
		    iw_sockets_close(skfd);
            break;

        case MODE_SET_ACTION:
                printf("bitrate MODE_SET_ACTION\n");
            /* perform the value change here */
	    ret = set_channel(skfd, INTERFACE, (char**)&(requests->requestvb->val.string), 1);
            if (ret <= 0) {
                netsnmp_set_request_error(reqinfo, requests, ret);
            }
            break;

        case MODE_SET_COMMIT:
                printf("bitrate MODE_SET_COMMIT\n");
            /* delete temporary storage */
	    if(skfd >= 0)
		    iw_sockets_close(skfd);
            break;

        case MODE_SET_UNDO:
                printf("bitrate MODE_SET_UNDO\n");
            break;

        default:
            /* we should never get here, so this is a really bad error */
            snmp_log(LOG_ERR, "unknown mode (%d) in handle_channel\n", reqinfo->mode );
            return SNMP_ERR_GENERR;
    }

    printf("bitrate - return\n");
    return SNMP_ERR_NOERROR;
}
Example #17
0
static void
shutdown_iw(void)
{
	iw_sockets_close(skfd);
}
Example #18
0
int main(int argc, const char **argv) {
	/* Check uid */
	if (getuid() != 0) {
		fprintf(stderr,"Swifer must be run as root.\n");
		return 1;
	}
	/* Check config file for interface and dhcp */
	FILE *cfg;
	if ( (cfg=fopen(config,"r")) ) {
		char *line = calloc(MAX_LINE+1,sizeof(char));
		char *val = calloc(MAX_LINE+1,sizeof(char));
		while (fgets(line,MAX_LINE,cfg) != NULL) {
			if (line[0] == '#') continue;
			if (sscanf(line,"INTERFACE = %s",val))
				strncpy(ifname,val,IFNAMSIZ);
			else if (sscanf(line,"DHCP = %s",val))
				strncpy(dhcp,val,DHCPLEN);
			else if (sscanf(line,"PRE_UP = %s",val))
				hook_preup = strdup(val);
			else if (sscanf(line,"POST_UP = %s",val))
				hook_postup = strdup(val);
			else if (strncmp(line,"[NETWORKS]",10)==0)
				break;
		}
		free(line); free(val); fclose(cfg);
	}
	/* Get basic wifi info */
	we_ver = iw_get_kernel_we_version();
	skfd = iw_sockets_open();
	iw_get_basic_config(skfd,ifname,&cur);
	/* Bring up interface (eg "ip link set IFACE up") */
	struct ifreq req;
	int err;
	strncpy(req.ifr_name,ifname,IFNAMSIZ);
	if ( (err=ioctl(skfd,SIOCGIFFLAGS,&req)) ){
		int loop = 0;
		while ( (err=ioctl(skfd,SIOCGIFFLAGS,&req)) ) {
			usleep(100000);
			if (loop++ > 50) break;
		}
		if (err) {
			close(skfd);
			return 2;
		}
	}
	req.ifr_flags |= IFF_UP;
	if (ioctl(skfd,SIOCSIFFLAGS,&req)) {
		close(skfd); return 3;
	}
	/* Processes command line arguments */
	int i;
	for (i = 1; i < argc; i++) {
		if (strncmp(argv[i],"ad",2)==0) mode |= MODE_ADD;
		else if (strncmp(argv[i],"au",2)==0) mode |= MODE_AUTO;
		else if (strncmp(argv[i],"hi",2)==0) mode |= MODE_HIDDEN;
		else if (strncmp(argv[i],"an",2)==0) mode |= (MODE_ANY | MODE_AUTO);
		else if (strncmp(argv[i],"re",2)==0) mode |= (MODE_RECONNECT | MODE_AUTO);
		else if (strncmp(argv[i],"ve",2)==0) mode |= MODE_VERBOSE;
		else if (strncmp(argv[i],"wa",2)==0) mode |= MODE_WAIT;
		else if (strncmp(argv[i],"de",2)==0) {
			if (argc > i+1) remove_network(argv[i+1]);
		}
		else fprintf(stderr,"[%s] Ignoring unknown parameter: %s\n",
			argv[0],argv[i]);
	}
	if ( (mode & MODE_VERBOSE) && (mode & MODE_AUTO) ) mode &= ~MODE_VERBOSE;
	/* Scan and select network */
	iw_scan(skfd,ifname,we_ver,&context);
	wireless_scan *ws;
	if (mode & MODE_AUTO) {
		if (mode && MODE_WAIT) {
			int loops;
			/* keep trying for up to 5 minutes */
			for (loops = 0; loops < 30 && !(ws=get_best()); ++loops)
				sleep(TIMEOUT);
		}
		else ws = get_best();
	}
	else ws = show_menu();
	const char *arg[4];
	if (ws) { /* Stop any current processes then connect to "ws" */
		arg[0] = killall; arg[1] = dhcp; arg[2] = NULL;
		if (fork()==0) {
			fclose(stdout); fclose(stderr);
			execvp(arg[0],(char * const *) arg);
		}
		arg[1] = wpa_sup;
		if (fork()==0) {
			fclose(stdout); fclose(stderr);
			execvp(arg[0],(char * const *) arg);
		}
		sleep(1);
		if ( (mode & MODE_ADD) && is_known(ws) ) mode &= ~MODE_ADD;
		if (ws->b.key_flags == 2048) mode |= MODE_SECURE;
		mode_t pre = umask(S_IWGRP|S_IWOTH|S_IRGRP|S_IROTH);
		ws_connect(ws);
		umask(pre);
	}
	else if ( !(mode & MODE_RECONNECT) ) {
		fprintf(stderr,"[swifer] no suitable networks found.\n");
		return 5;
	}
	/* Keep alive to reconnect? */
	iw_sockets_close(skfd);
	if (mode & MODE_RECONNECT) {
		if (fork() == 0) {
			setsid();
			int level = THRESHOLD + 1, ret;
			char scanline[256];
			snprintf(scanline,255,"%%*[^\n]\n%%*[^\n]\n%s: %%*d %%d.",ifname);
			FILE *procw;
			while (level > THRESHOLD) {
				sleep(TIMEOUT);
				procw = fopen(PROC_NET_WIRELESS,"r");
				ret = fscanf(procw,scanline,&level);
				fclose(procw);
				if (ret != 1) level = 0;
			}
			arg[0] = argv[0]; arg[1] = re; arg[2] = an; arg[3] = NULL;
			if ( !(mode & MODE_ANY)) arg[2] = NULL;
			execvp(arg[0],(char * const *) arg);
		}
	}
	if (hook_preup) free(hook_preup);
	if (hook_postup) free(hook_postup);
	return 0;
}
Example #19
0
nsresult
nsWifiMonitor::DoScan()
{
  void* iwlib_handle = dlopen("libiw.so", RTLD_NOW);
  if (!iwlib_handle) {
    iwlib_handle = dlopen("libiw.so.29", RTLD_NOW);
    if (!iwlib_handle) {
      iwlib_handle = dlopen("libiw.so.30", RTLD_NOW);
      if (!iwlib_handle) {
        LOG(("Could not load libiw\n"));
        return NS_ERROR_NOT_AVAILABLE;
      }
    }
  }
  else {
    LOG(("Loaded libiw\n"));
  }

  iw_open_t iw_open = (iw_open_t) dlsym(iwlib_handle, "iw_sockets_open");
  iw_enum_t iw_enum = (iw_enum_t) dlsym(iwlib_handle, "iw_enum_devices");
  iw_stats_t iw_stats = (iw_stats_t)dlsym(iwlib_handle, "iw_get_stats");

  if (!iw_open || !iw_enum || !iw_stats) {
    dlclose(iwlib_handle);
    LOG(("Could not load a symbol from iwlib.so\n"));
    return NS_ERROR_FAILURE;
  }

  int skfd = (*iw_open)();

  if (skfd < 0) {
    dlclose(iwlib_handle);
    return NS_ERROR_FAILURE;
  }

  nsCOMArray<nsWifiAccessPoint> lastAccessPoints;
  nsCOMArray<nsWifiAccessPoint> accessPoints;

  char* args[] = {(char*) &accessPoints, (char*) iw_stats, nsnull };

  while (mKeepGoing) {

    accessPoints.Clear();

    (*iw_enum)(skfd, &scan_wifi, args, 1);

    PRBool accessPointsChanged = !AccessPointsEqual(accessPoints, lastAccessPoints);
    nsCOMArray<nsIWifiListener> currentListeners;

    {
      nsAutoMonitor mon(mMonitor);

      for (PRUint32 i = 0; i < mListeners.Length(); i++) {
        if (!mListeners[i].mHasSentData || accessPointsChanged) {
          mListeners[i].mHasSentData = PR_TRUE;
          currentListeners.AppendObject(mListeners[i].mListener);
        }
      }
    }

    ReplaceArray(lastAccessPoints, accessPoints);

    if (currentListeners.Count() > 0)
    {
      PRUint32 resultCount = lastAccessPoints.Count();
      nsIWifiAccessPoint** result = static_cast<nsIWifiAccessPoint**> (nsMemory::Alloc(sizeof(nsIWifiAccessPoint*) * resultCount));
      if (!result) {
        dlclose(iwlib_handle);
        return NS_ERROR_OUT_OF_MEMORY;
      }

      for (PRUint32 i = 0; i < resultCount; i++)
        result[i] = lastAccessPoints[i];

      for (PRInt32 i = 0; i < currentListeners.Count(); i++) {

        LOG(("About to send data to the wifi listeners\n"));

        nsCOMPtr<nsIWifiListener> proxy;
        nsCOMPtr<nsIProxyObjectManager> proxyObjMgr = do_GetService("@mozilla.org/xpcomproxy;1");
        proxyObjMgr->GetProxyForObject(NS_PROXY_TO_MAIN_THREAD,
                                       NS_GET_IID(nsIWifiListener),
                                       currentListeners[i],
                                       NS_PROXY_SYNC | NS_PROXY_ALWAYS,
                                       getter_AddRefs(proxy));
        if (!proxy) {
          LOG(("There is no proxy available.  this should never happen\n"));
        }
        else
        {
          nsresult rv = proxy->OnChange(result, resultCount);
          LOG( ("... sent %d\n", rv));
        }
      }

      nsMemory::Free(result);
    }

    LOG(("waiting on monitor\n"));

    nsAutoMonitor mon(mMonitor);
    mon.Wait(PR_SecondsToInterval(60));
  }

  iw_sockets_close(skfd);

  return NS_OK;
}
Example #20
0
/*
 * The main !
 */
int
main(int	argc,
     char **	argv)
{
  int	skfd;			/* generic raw socket desc.	*/
  int	format = FORMAT_DEFAULT;
  int	wtype = WTYPE_ESSID;
  int	opt;
  int	ret = -1;

  /* Check command line arguments */
  while((opt = getopt_long(argc, argv, "acfhmprs", long_opts, NULL)) > 0)
    {
      switch(opt)
	{
	case 'a':
	  /* User wants AP/Cell Address */
	  wtype = WTYPE_AP;
	  break;

	case 'c':
	  /* User wants channel only */
	  wtype = WTYPE_CHANNEL;
	  break;

	case 'f':
	  /* User wants frequency/channel */
	  wtype = WTYPE_FREQ;
	  break;

	case 'm':
	  /* User wants the mode */
	  wtype = WTYPE_MODE;
	  break;

	case 'p':
	  /* User wants the protocol */
	  wtype = WTYPE_PROTO;
	  break;

	case 'h':
	  iw_usage(0);
	  break;

	case 'r':
	  /* User wants a Raw format */
	  format = FORMAT_RAW;
	  break;

	case 's':
	  /* User wants a Scheme format */
	  format = FORMAT_SCHEME;
	  break;

	default:
	  iw_usage(1);
	  break;
	}
    }
  if(optind + 1 < argc) {
    fputs("Too many arguments.\n", stderr);
    iw_usage(1);
  }

  /* Create a channel to the NET kernel. */
  if((skfd = iw_sockets_open()) < 0)
    {
      perror("socket");
      return(-1);
    }

  /* Check if first argument is a device name */
  if(optind < argc)
    {
      /* Yes : query only this device */
      ret = print_one_device(skfd, format, wtype, argv[optind]);
    }
  else
    {
      /* No : query all devices and print first found */
      ret = scan_devices(skfd, format, wtype);
    }

  fflush(stdout);
  iw_sockets_close(skfd);
  return(ret);
}
Example #21
0
/*
 * The main !
 */
int
main(int	argc,
     char **	argv)
{
  int skfd;			/* generic raw socket desc.	*/
  char *dev;			/* device name			*/
  char *cmd;			/* command			*/
  char **args;			/* Command arguments */
  int count;			/* Number of arguments */
  const iwlist_cmd *iwcmd;

  if(argc == 1 || argc > 3)
    iw_usage(1);

  /* Those don't apply to all interfaces */
  if((argc == 2) && (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")))
    iw_usage(0);
  if((argc == 2) && (!strcmp(argv[1], "-v") || !strcmp(argv[1], "--version")))
    return(iw_print_version_info("iwlist"));

  if(argc == 2)
    {
      cmd = argv[1];
      dev = NULL;
      args = NULL;
      count = 0;
    }
  else
    {
      cmd = argv[2];
      dev = argv[1];
      args = argv + 3;
      count = argc - 3;
    }

  /* find a command */
  iwcmd = find_command(cmd);
  if(iwcmd == NULL)
    return 1;

  /* Check arg numbers */
  if(count < iwcmd->min_count)
    {
      fprintf(stderr, "iwlist: command `%s' needs more arguments\n", cmd);
      return 1;
    }
  if(count > iwcmd->max_count)
    {
      fprintf(stderr, "iwlist: command `%s' needs fewer arguments\n", cmd);
      return 1;
    }

  /* Create a channel to the NET kernel. */
  if((skfd = iw_sockets_open()) < 0)
    {
      perror("socket");
      return -1;
    }

  /* do the actual work */
  if (dev)
    (*iwcmd->fn)(skfd, dev, args, count);
  else
    iw_enum_devices(skfd, iwcmd->fn, args, count);

  /* Close the socket. */
  iw_sockets_close(skfd);

  return 0;
}
Example #22
0
WifiStumbler::~WifiStumbler()
{
  iw_sockets_close(wlan_sock_);
}