Skip to content

Improvement for Linux: retrieve password from wpa_supplicant.conf #1

Description

@hyppoCom

Hope someone find it useful (Linux only)
Improvements:

  • Retrieve password from wpa_supplicant.conf if password not given
  • Avoid segfault if password not given in args or automatically retrieved
--- main.c	2019-05-19 18:06:53.000000000 +0200
+++ main.c	2019-09-09 00:56:09.229406654 +0200
@@ -113,9 +113,55 @@
 	}
 }
 
+#if (defined _LINUX)
+char *get_config_value(char *ptr)
+{
+	char *eptr;
+	while((*ptr=='\t' || *ptr==' ' || *ptr=='=' || *ptr=='"') && *ptr!='\0') ptr++;
+	eptr=ptr+strlen(ptr)-1;
+	while(eptr>ptr && (*eptr=='\t' || *eptr==' ' || *eptr=='"')) {
+		if(*eptr=='"') {
+			*eptr='\0';
+			break;
+		}
+		*eptr='\0';
+		eptr--;
+	}
+	return(ptr);
+}
+
+const char *get_wpa_supplicant_password(char *essid)
+{
+	static char *pass=NULL;
+	char buf[256],*ptr;
+	int status=0;
+	FILE *FP=fopen("/etc/wpa_supplicant/wpa_supplicant.conf","r");
+	if(!FP) return(pass);
+	while(fgets(buf,sizeof(buf)-1,FP)) {
+		if(buf[0]!='\0') buf[strlen(buf)-1]='\0';
+		ptr=&buf[0];
+		while((*ptr=='\t' || *ptr==' ') && *ptr!='\0') ptr++;
+		if(*ptr=='}') {
+			status=0;
+		} else if(strncmp(ptr,"network",7)==0) {
+			status=1;
+		} else if(strncmp(ptr,"ssid",4)==0) {
+			ptr=get_config_value(ptr+4);
+			if(strcmp(ptr,essid)==0) status=2;
+		} else if(status==2 && strncmp(ptr,"psk",3)==0) {
+			ptr=get_config_value(ptr+3);
+			pass=strdup(ptr);
+			break;
+		}
+	}
+	fclose(FP);
+	return(pass);
+}
+#endif
+
 int main(int argc, char* argv[])
 {
-	printf("%s, ver: " COMPILE_TIMESTAMP " ...\n", argv[0]);
+	printf("%s, ver: " COMPILE_TIMESTAMP " ...\n", basename(argv[0]));
 	
 	scanargs(argc, argv);
 
@@ -152,7 +198,18 @@
 		
 		printf("using ssid %s (%s)\n", essid, bssid);
 	}
+
+	if (essid !=NULL && passwd == NULL)
+	{
+		passwd=get_wpa_supplicant_password((char *)essid);
+		printf("retrieving password for ssid %s\n", essid);
+	}
 #endif
+	if (passwd == NULL)
+	{
+		eprintf("missing password for %s.\n", essid);
+		return EXIT_FAILURE;
+	}
 
 	esp_smartcfg_run(essid, bssid, passwd, ownaddr, hidden, timeout);


Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions