#include "config.h" #ifndef lint static char rcsid[] ATTR_UNUSED = "$Id$"; #endif #include "setup.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef HAVE_GETOPT_LONG #include #else #include "getopt.h" #endif #define NELEM(x) (sizeof((x))/sizeof(*(x))) #ifndef DEBUG #define dbg(cmd) #else #define dbg(cmd) cmd #endif /* ANSI C does not allow macro with variable arguments */ #define dO stderr #define dB(a) dbg(fprintf a) #define d1(n1) dB((dO,n1 )) #define d2(n1,n2) dB((dO,n1,n2 )) #define d3(n1,n2,n3) dB((dO,n1,n2,n3 )) #define d4(n1,n2,n3,n4) dB((dO,n1,n2,n3,n4)) static const char version[]="This is Nokia 9110 logo SMS sender (" PACKAGE " " VERSION ")\n"; static int verbose #ifdef DEBUG =0xFFFF #endif ; static char *pname; static int dis_cleanup=0,devfd=-1; static char *phone,*logoname,*device,*logname,*lockfile,*smsc,*maxretry,*readtime,*chartime,*cmdtime,*baud,*gsmnet; static long maxretryn=DEF_MAXRETRY,readtimen=DEF_READTIME,chartimen=DEF_CHARTIME,cmdtimen=DEF_CMDTIME,baudn=DEF_BAUD; static char *devicename; /* path stripped */ static char lockreal[512],locked; static struct termios restios,tios; static char restios_yes; static FILE *logf; static void vlogmsg(char outerr, const char *fmt,va_list ap) ATTR_PRINTFORMAT(2,0); static void vlogmsg(char outerr, const char *fmt,va_list ap) { time_t stamp; char *ctm,*s; pid_t mypid=-1; char host[LINE_MAX]; if (!logf) return; if (mypid==-1) { mypid=getpid(); if (gethostname(host,sizeof(host))) strcpy(host,""); } time(&stamp); ctm=ctime(&stamp); if ((s=strchr(ctm,'\n'))) *s='\0'; fprintf(logf,"%s %s %s[%d]: ",ctm,host,pname,mypid); vfprintf(logf,fmt,ap); if (outerr) fputs(strerror(errno),logf); fputc('\n',logf); fflush(logf); } static void logmsg(const char *fmt,...) ATTR_PRINTFORMAT(1,2); static void logmsg(const char *fmt,...) { va_list ap; va_start(ap,fmt); vlogmsg(0,fmt,ap); va_end(ap); } static void error(const char *fmt,...) ATTR_PRINTFORMAT(1,2); static void error(const char *fmt,...) { va_list ap; char fatal,pm; if ((pm=(*fmt=='^'))) fmt++; fatal=*fmt; if (fatal=='!' || fatal=='.' || fatal=='\n') fmt++; else fatal=0; fprintf(stderr,"%s: ",pname); va_start(ap,fmt); vfprintf(stderr,fmt,ap); if (fatal=='!') vlogmsg(pm,fmt,ap); va_end(ap); if (pm) { fputs(": ",stderr); fputs(strerror(errno),stderr); } if (fatal!='\n') fputc((fatal=='.'?'.':'!'),stderr); fputc('\n',stderr); if (fatal=='!') exit(EXIT_FAILURE); } static void chk(void *p) { if (p) return; error("!Virtual memory exhausted"); } static void cleanup(void) { d1("cleanup()\n"); if (dis_cleanup) return; if (restios_yes) { if (tcsetattr(devfd,TCSANOW,&restios)) error("^Error restoring termios for device"); restios_yes=0; } if (locked && *lockreal) { d2("Removing lockfile \"%s\"\n",lockreal); if (unlink(lockreal)) error("^Error removing my device lockfile \"%s\"",lockreal); locked=0; } dis_cleanup=1; exit(EXIT_FAILURE); } static void usage(void) { fprintf(stderr,"\ \n\ %s\ \n\ Usage: " PACKAGE " [-c|--config ] [-d|--device ]\n\ [-L|--log ] [-b|--baud ]\n\ [-l|--lockfile ] [-s|--smsc ] [-m|--maxretry <#>]\n\ [-r|--readtime ] [-t|--chartime ] [-T|--cmdtime ]\n\ [-v|--verbose] [-h|--help] [-V|--version]\n\ []\n\ \n\ -c, --config\tRead this additional config file\n\ \t\t(def. \"" CONFIG_MAIN "\" and \"$HOME" CONFIG_HOME "\")\n\ -d, --device\tNokia on this serial device (def. \"" DEF_DEVICE "\")\n\ -L, --log\tLog all important messages to this file (def. \"" DEF_LOGNAME "\")\n\ -b, --baud\tSet baudrate, 2400-57600 supported (def. %d)\n\ -l, --lockfile\tLock serial port by this file, \"%%s\" is basename of device\n\ \t\t(def. \"%s\")\n\ -s, --smsc\tUse this SMS Center number (def. query from Nokia 9110)\n\ -m, --maxretry\tMaximum retries of any command before giving up (def. %d)\n\ -r, --readtime\tSeconds for maximum wait time for response (def. %ds)\n\ -t, --chartime\tMilliseconds between each char (def. %dms)\n\ -T, --cmdtime\tMilliseconds before each whole AT command (def. %dms)\n\ -v, --verbose\tIncrease verbosity level, more \"-v\"s give more messages\n\ -h, --help\tPrint a summary of the options\n\ -V, --version\tPrint the version number\n\ \t* Oper. logo: Enter custom network code MccMnc, e.g. 23002\n\ \t\t* Oper. logo: Specify \"" WORD_NET "\" to read network code from NOL file\n\ \t\t* Group gfx : Specify \"" WORD_GROUP "\" to send logo as group graphics\n\ \n",version,DEF_BAUD,DEF_LOCKFILE,DEF_MAXRETRY,DEF_READTIME,DEF_CHARTIME,DEF_CMDTIME); exit(EXIT_FAILURE); } static const struct option longopts[]={ {"config" ,1,0,'c'}, {"device" ,1,0,'d'}, {"log" ,1,0,'L'}, {"baud" ,1,0,'b'}, {"lockfile",1,0,'l'}, {"smsc" ,1,0,'s'}, {"maxretry",1,0,'m'}, {"readtime",1,0,'r'}, {"chartime",1,0,'t'}, {"cmdtime" ,1,0,'T'}, {"verbose" ,0,0,'v'}, {"help" ,0,0,'h'}, {"version" ,0,0,'V'}}; static void processargs(int argp,char **args,const char *from); static char *cfgstack[MAXCFGLOOP]; static unsigned cfgstacki=0; static void chkfclose(FILE *f,const char *fname) { if (fclose(f)) error("^Error closing \"%s\"",fname); } static void readfile(const char *fname,char quiet) { FILE *f; size_t got; char *args[MAXCFGARGS],*d,*s,blank,quote; unsigned argp; char *buf; long size; static unsigned tot=0; if (tot++>=MAXCFGNUM) { if (tot==MAXCFGNUM+1) error("Too many config files to read, max is %d, break-out",MAXCFGNUM); return; } if (!(f=fopen(fname,"rt"))) { if (!quiet) error("^Can't open config file \"%s\" for r/o",fname); return; } if (verbose>=2) error(".Reading config file \"%s\"",fname); if (fseek(f,0,SEEK_END)) error("^Error seeking to end of \"%s\"",fname); if ((size=ftell(f))<0) size=0,error("^Error measuring \"%s\"",fname); if (size>MAXCONFIG) error("File \"%s\" is too long, read only %d bytes",fname,MAXCONFIG); chk(buf=malloc((size?size:MAXCONFIG)+1)); rewind(f); got=fread(buf,1,(size?size:MAXCONFIG),f); if (size && got!=size) error("File \"%s\" read error, got only %u bytes of %ld",fname,got,size); chkfclose(f,fname); buf[got]='\0'; args[0]=pname; for (argp=1,d=s=buf,blank=1,quote=0;s=2) error("\nConfig \"%s\": arg#%d: %s",fname,argp-1,args[argp-1]); } continue; } if (blank) { if (argp>=NELEM(args)-1) { error("Too many arguments in \"%s\", from offset %d ignored",fname,s-buf); break; } args[argp++]=s; d=s; blank=0; } if (c=='\\') { *d++=*++s; continue; } if (c=='"' || c=='\'') { if (!quote ) { quote=c; continue; } if ( quote==c) { quote=0; continue; } /* FALLTHRU */ } *d++=c; } args[argp]=NULL; processargs(argp,args,fname); free(buf); } static struct { const char c; char **const var; unsigned stamp; } optset[]={ { 'd',&device }, { 'L',&logname }, { 'b',&baud }, { 'l',&lockfile }, { 's',&smsc }, { 'm',&maxretry }, { 'r',&readtime }, { 't',&chartime }, { 'T',&cmdtime }, }; static void processargs(int argp,char **args,const char *from) { int optc; static unsigned seq=0; int i; seq++; optarg=NULL; optind=0; /* FIXME: Possible portability problem. */ while ((optc=getopt_long(argp,args,"c:d:L:b:l:s:m:r:t:T:fvhV",longopts,NULL))!=EOF) switch (optc) { case 'c': if (cfgstacki>=NELEM(cfgstack)) { error("Looping (%d) during attempt to read config file \"%s\", break-out",NELEM(cfgstack),from); break; } chk(cfgstack[cfgstacki++]=strdup(optarg)); break; case 'd': case 'L': case 'b': case 'l': case 's': case 'm': case 'r': case 't': case 'T': for (i=0;i=0); readfile(s,0); free(s); assert(cfgstacki>=0 && cfgstacki=3) error(".Checking the lockfile \"%s\"..",lockreal); if ((fd=open(lockreal,O_RDONLY))==-1) break; if ((got=read(fd,buf,sizeof(buf)-1))<=0) { isempty: if (empty>=DEVLOCK_MAXEMPTY) { error(".Lockfile \"%s\" is still not valid, removing it",lockreal); goto remove; } empty++; continue; } assert(got=1) error("Timed out"); } static void blocking(char yes) { static char state=-1; if (state==yes) return; if (fcntl(devfd,F_SETFL,(yes?0:O_NONBLOCK))) error("^!fcntl() on device for %sblocking mode",(yes?"":"non-")); state=yes; } static const char *record; static char *catchdata; static size_t catchdatal,catchdatasiz; static void catched(const char *end) { size_t len; void *p; if (!record) return; assert(end>=record); if ((p=memchr(record,'\n',end-record))) end=p; if ((len=end-record)) { if (catchdatal+len>catchdatasiz) chk(catchdata=realloc(catchdata, (catchdatasiz=MAX(LINE_MAX,(catchdatal+len)*2)))); memcpy(catchdata+catchdatal,record,len); catchdatal+=len; } record=(p?NULL:end); assert(catchdatal<=catchdatasiz); } static int retrycnt=0; static void retrying(void) { if (++retrycnt>maxretryn) error("!Maximum command retry count (%ld) exceeded",maxretryn); if (verbose>=2) error(".Retrying phase, %d out of %ld..",retrycnt,maxretryn); } static char *devcmd(const char *term,const char *catch,const char *send,...) ATTR_PRINTFORMAT(3,4); static char *devcmd(const char *term,const char *catch,const char *send,...) { size_t l,bufl,terml,catchl,fragl,offs; char buf[LINE_MAX]; ssize_t got; char *hit,*s; va_list ap; char errout; if (!term) term="\nOK\n"; if ((errout=(*send=='!'))) send++; if (0) { err: alarm(0); if (errout) return(NULL); retrying(); } catchdatal=0; va_start(ap,send); l=VARVPRINTF(buf,send,ap); bufl=l+1; va_end(ap); if (bufl>=sizeof(buf)-1) error("!Command too big (%d>%d)",bufl,sizeof(buf)-1); if (verbose>=2) error(".devcmd(send=\"%s\",term=\"%s\",catch=\"%s\")",buf,term,catch); buf[l]='\r'; buf[l+1]='\n'; for (offs=0,got=0;offss && (s=memchr(s,'\r',buf+bufl-s))) *s='\n'; catched(buf+bufl); assert(!record || record==buf+bufl); assert(bufl=fragl) { buf[bufl]='\0'; assert(strlen(buf)==bufl); /* d3(">%s|%s<\n",buf,term); */ if (strstr(buf,ERROR_SUBSTR1) || strstr(buf,ERROR_SUBSTR2)) { error("Found ERROR response on command \"%s\"",send); goto err; } if (catch && bufl>=catchl && (hit=strstr(buf,catch))) { record=hit+catchl; catched(buf+bufl); assert(!record || record==buf+bufl); } if ( bufl>= terml && (hit=strstr(buf,term))) break; memmove(buf,buf+bufl-(fragl-1),fragl-1); bufl=fragl-1; if (record) record=buf+bufl; } } alarm(0); if (!catchdatal) { if (!catch) return(NULL); error("Data requested on command \"%s\" but no found after term \"%s\"",send,term); goto err; } assert(!!catch); record=buf; buf[0]='\0'; catched(buf+1); if (verbose>=2) error(".Returning data \"%s\" for cmd \"%s\"",catchdata,send); return(catchdata); } static inline char tohex(unsigned char x) { x&=0x0F; if (x<10) return(x +'0'); return(x-10+'A'); } static inline void textconv(char *d,unsigned char *s,size_t len) { while (len--) { *d++=tohex(*s>>4U); *d++=tohex(*s ); s++; } *d='\0'; } static inline void smscset(void) { char *s,*t,*e,*serr; long l; if (smsc) devcmd(NULL,NULL,"\r\nAT+CSCA=\"%s\"",smsc); s=devcmd(NULL,"\n+CSCA:","\r\nAT+CSCA?"); while (isspace(*s)) s++; if (!*s || !strcmp(s,"EMPTY")) error("!No SMS set in Nokia found"); if (verbose>=1) error("\nFound default SMSC in Nokia: %s",s); if (*s!='"') error("!No left-quote found in: %s",s); if (!(t=strrchr(s+1,'"'))) error("!No right-quote found in: %s",s); e=t++; while (isspace(*t)) t++; if (*t++!=',') error("!No comma found after quotes in: %s",s); while (isspace(*t)) t++; l=strtol(t,&serr,10); if ((l!=ADDR_NAT && l!=ADDR_INT) || (serr && *serr)) error("!Type parse error in: %s",s); if (l==ADDR_NAT || s[1]=='+') s++; else *s='+'; *e='\0'; if (verbose>=2) error("\nDecoded SMSC address: %s",s); } /* Logo format shamelessly stolen from GNokii-0.3.0: http://www.gnokii.org/ * Beware - Nokia Smart Messaging specification 1.0.0 and 2.0.0 is incompatible * with Nokia current product line implementation * http://www.forum.nokia.com/developers/smartmsg/download/ssm2_0_0.pdf */ static char hexdata[140*2+1]; static inline void logoread(void) { FILE *f; char buf[32+140*8+1]; unsigned char bin[140]={ 0x06, /* UDH length */ 0x05, /* IEI */ 0x04, /* IEDL */ 0x15, 0x83, /* dest port (group gfx) */ 0x00, 0x00 /* src port (unused) */ }; size_t got,r,w; ssize_t chars,bits; char gsmnetf[10]; int sizex,sizey,bit; #define WORD(n) (((unsigned char)buf[(n)])|(((unsigned char)buf[(n)+1])<<8)) if (!(f=fopen(logoname,"rb"))) error("^!Cannot open logo file \"%s\" for r/o",logoname); got=fread(buf,1,sizeof(buf),f); if (got>=20 && !memcmp(buf,"NOL",4)) { VARPRINTF2(gsmnetf,"%03.3u%02.2u",WORD(6),WORD(8)); assert(strlen(gsmnetf)==5); r=10; if (verbose>=1) error(".Reading NOL file \"%s\", GSMnet \"%s\", word@4=%d..", logoname,gsmnetf,WORD(4)); } else if (got>=16 && !memcmp(buf,"NGG",4)) { r=6; if (verbose>=1) error(".Reading NGG file \"%s\", word@4=%d..", logoname,WORD(4)); } else error("!Unknown file format of logo file \"%s\"",logoname); if (!strcasecmp(gsmnet,WORD_NET)) { if (!*gsmnetf) error("!NOL network code detection requested but NOL file not loaded, please specify network code"); gsmnet=gsmnetf; } if (!strcasecmp(gsmnet,WORD_GROUP) || !*gsmnet) { error("\nSending logo as: group graphics"); gsmnet=NULL; } else { error("\nSending logo as: operator logo for \"%s\"",gsmnet); bin[4]=0x82; /* dest port 0x1582 */ } sizex=WORD(r); sizey=WORD(r+2); if (verbose>=2) error(".Magic words: @+4=%d, @+6=%d, @+8=%d", WORD(r+4),WORD(r+6),WORD(r+8)); r+=10; if (sizex<1 || sizex>255 || sizey<1 || sizey>255) error("!Invalid size: %dx%d",sizex,sizey); chars=((bits=sizex*sizey)+7)/8; if (r+bits>got) error("!Logo file \"%s\" too short - actual=%d, need(%dx%d)=%d", logoname,got,sizex,sizey,r+chars); else if (r+bits=1) error("Ignoring trailing garbage in \"%s\", used only %d bytes",logoname,r+bits); if ((got=(7+(gsmnet?3:0)+4+chars))>140) error("!SMS size would be %d bytes but 140 is maximum",got); w=7; if (gsmnet) { bin[w++]=((gsmnet[1]&0x0F)<<4)|(gsmnet[0]&0x0F); bin[w++]=0xF0 |(gsmnet[2]&0x0F); bin[w++]=((gsmnet[4]&0x0F)<<4)|(gsmnet[3]&0x0F); } bin[w++]=0x00; /* RFU by Nokia */ bin[w++]=sizex; bin[w++]=sizey; bin[w++]=0x01; /* one B/W plane */ while (chars--) { bin[w]=0; for (bit=0x80;(bits>0) && (bit>0);bits--,bit>>=1) { if (buf[r]!='0' && buf[r]!='1') error("!Invalid character (neither '0' nor '1')in logo file \"%s\" at offset 0x%X", logoname,r); if (buf[r++]=='1') bin[w]|=bit; } w++; } assert(chars==-1); assert(bits==0); assert(w==got); assert(w<=140); textconv(hexdata,bin,w); if (verbose>=2) error("\nWill send hexdata: %s",hexdata); #undef WORD } static struct { char **sp; long *ip; const char *const msg; } numarg[]={ { &maxretry,&maxretryn,"maxretry" }, { &readtime,&readtimen,"readtime" }, { &chartime,&chartimen,"chartime" }, { &cmdtime ,&cmdtimen ,"cmdtime" }, { &baud ,&baudn ,"baud" }, }; int main(int argc,char **argv) { char *s; int i; unsigned fatal=0; speed_t portbaud; if ((s=strrchr((pname=*argv),'/'))) pname=s+1; atexit(cleanup); signal(SIGTERM,(RETSIGTYPE (*)(int))cleanup); signal(SIGQUIT,(RETSIGTYPE (*)(int))cleanup); signal(SIGINT ,(RETSIGTYPE (*)(int))cleanup); signal(SIGHUP ,(RETSIGTYPE (*)(int))cleanup); processargs(argc,argv,""); if ((s=getenv("HOME"))) { size_t l=strlen(s); char *buf=malloc(l+50); memcpy(buf,s,l); strcpy(buf+l,CONFIG_HOME); readfile(buf,1); free(buf); } readfile(CONFIG_MAIN,1); for (i=0;i=LONG_MAX || !serr || *serr) error("!Number parse error for parameter \"%s\" of \"%s\" at: %s", numarg[i].msg,*numarg[i].sp,serr); } if (!strchr(device,'/')) { size_t l=strlen(device); chk(s=malloc(5+l+1)); strcpy(s,"/dev/"); strcpy(s+5,device); free(device); device=s; } devicename=strrchr(device,'/')+1; assert(!!(devicename-1)); for (i=0,s=lockfile;*s;s++) { if (*s!='%') continue; s++; if (*s=='%') continue; if (*s=='s') { if (i) error("!Only one \"%%s\" permitted in lockfile format-string"); i=1; continue; } error("!Invalid format-character '%c' in lockfile format-string, only \"%%s\" allowed",*s); } if (*logname) { if (!(logf=fopen(logname,"a"))) error("^!Error opening log \"%s\" for append",logname); logmsg("Starting up: " PACKAGE " " VERSION); } switch (baudn) { case 2400: portbaud= B2400; break; case 4800: portbaud= B4800; break; case 9600: portbaud= B9600; break; case 19200: portbaud=B19200; break; case 38400: portbaud=B38400; break; case 57600: portbaud=B57600; break; default: error("!Specified baudrate %ld is not supported",baudn); } if (verbose>=2) error(".Will use baudrate %ld with hexval 0x%X",baudn,portbaud); if (lockfile && *lockfile && VARPRINTF(lockreal,lockfile,devicename)>0) { time_t start,end; if (verbose>=1) error(".Locking device \"%s\" by \"%s\"..",device,lockreal); time(&start); lockdevice(); time(&end); if ((end-=start)>LOCKREPORT) logmsg("Device lock succeeded after %ld seconds",(long)end); } if (verbose>=1) error(".Opening device \"%s\"..",device); if ((devfd=open(device,O_RDWR|O_NDELAY))<0) error("^!Cannot open device \"%s\" for rw-access",device); if (tcgetattr(devfd,&restios)) error("^Unable to get termios settings"); else { restios.c_cflag=(restios.c_cflag&~(CBAUD|CBAUDEX))|B0|HUPCL; restios_yes=1; } tios.c_iflag=IGNBRK|IGNPAR|IXON|IXOFF; tios.c_oflag=0; tios.c_cflag=CS8|CREAD|CLOCAL|HUPCL|portbaud; tios.c_lflag=IEXTEN|NOFLSH; memset(tios.c_cc,_POSIX_VDISABLE,sizeof(tios.c_cc)); tios.c_cc[VTIME]=0; tios.c_cc[VMIN ]=1; cfsetispeed(&tios,portbaud); if (cfsetospeed(&tios,portbaud)|cfsetispeed(&tios,portbaud)) error("^Error setting termios baudrate on device"); if (tcflush(devfd,TCIOFLUSH)) error("^Error flushing termios (TCIOFLUSH) on device"); if (tcsetattr(devfd,TCSANOW,&tios)) error("^!Unable to set initial termios device settings"); setalarm(); do { devcmd("",NULL,"\r\nAT\033"); devcmd(NULL,NULL,"\r\nAT"); smscset(); devcmd(NULL,NULL,"\r\nAT+CSMP=81,,0,245"); devcmd("\n> ",NULL,"\r\nAT+CMGS=\"%s\"",phone); if (!(s=devcmd(NULL,"\n+CMGS:","!%s\032",hexdata))) { retrying(); continue; } devcmd(NULL,NULL,"\r\nAT+CSMP=17,,0,0"); devcmd(NULL,NULL,"\r\nAT"); } while (0); while (isspace(*s)) s++; if (verbose>=1) error("\nMessage successfuly sent with MR: %s",s); devcmd(NULL,NULL,"\r\nAT"); logmsg("SMS sent (after %d retries), message reference: %s",retrycnt,s); return(EXIT_SUCCESS); }