#include #include #include #include #include #include "config.h" config_t config = { .SMS_INBOX = "", .SMS_SENTBOX = "", .SMS_OUTBOX = "", .MMS_DIR = "", .CONTACT_FILENAME = ""}; const char* search_key[]= {"SMS_INBOX", "SMS_SENTBOX", "SMS_OUTBOX", "MMS_DIR", "CONTACT_FILENAME"}; int searchConfigFile(char* configFile) { // Search a config file. // First then in the home, then in /etc and finaly in /var. // In debug mode, this function search in ./fixtures const char* paths[] = {"/etc/mesmsrc", "/var/spool/sms/mesmsrc"}; FILE* f_canRead = NULL; char path[256] = ""; #ifdef DEBUG // If debug, local dir first getcwd(path, 256); strcat(path, "/mesmsrc"); f_canRead = fopen(path, "r"); if( f_canRead ) { fclose(f_canRead); strcpy(configFile, path); return 0; } getcwd(path, 256); strcat(path, "/.mesmsrc"); f_canRead = fopen(path, "r"); if( f_canRead ) { fclose(f_canRead); strcpy(configFile, path); return 0; } #endif // Home first char* home; struct passwd* pw = getpwuid(getuid()); home = pw->pw_dir; if( !*home ) home = getenv("HOME"); sprintf(path, "%s/.mesmsrc", home); f_canRead = fopen(path, "r"); if( f_canRead ) { fclose(f_canRead); strcpy(configFile, path); return 0; } for( int i = 0 ; i < sizeof paths / sizeof *paths ; i++) { f_canRead = fopen(paths[i], "r"); if( f_canRead ) { fclose(f_canRead); strcpy(configFile, paths[i]); return 0; } } #ifdef DEBUG fprintf(stderr, "No config file found\n"); #endif return 1; } int readConfigFile(void) { char fileName[256] = ""; if( searchConfigFile(fileName) > 0 ) { return 1; } FILE* file = fopen(fileName, "r"); char line[300] = ""; if( file ) { while(fgets(line, 300, file) != NULL) { char* tmp = strrchr(line, '\n'); if( tmp ) *tmp = 0; int elem = -1; for( int i = 0 ; i < sizeof search_key / sizeof *search_key ; i++) { if( strncmp(line, search_key[i], strlen(search_key[i])) == 0 ) { elem = i; break; } } if(elem >= 0) { char* res = NULL; if(strchr(line, '\"')) { strtok(line, "\""); res = strtok(NULL, "\""); } else if(strchr(line, '=')) { strtok(line, "="); res = strtok(NULL, "="); } else { continue; } char* configProperty = ((char*[]){config.SMS_INBOX, config.SMS_SENTBOX, config.SMS_OUTBOX, config.MMS_DIR, config.CONTACT_FILENAME})[elem]; int r = 0; if( !res ) res = ""; if( strlen(res) > 255 ) continue; wordexp_t p; r = wordexp(res, &p, 0); if( r == 0) { if( p.we_wordc > 0 ) strncpy( configProperty, p.we_wordv[0], 255); wordfree(&p); } else { strncpy( configProperty, res, 255); } #ifdef DEBUG fprintf(stderr, "%s is \"%s\"\n", search_key[elem], configProperty ); #endif } } } #ifdef DEBUG else { fprintf(stderr, "Error reading config file [%s]\n", fileName); } #endif }