3 static char rcsid[] ATTR_UNUSED = "$Id$";
19 #include <sys/types.h>
26 #ifdef HAVE_GETOPT_LONG
32 #define NELEM(x) (sizeof((x))/sizeof(*(x)))
39 /* ANSI C does not allow macro with variable arguments */
41 #define dB(a) dbg(fprintf a)
43 #define d1(n1) dB((dO,n1 ))
44 #define d2(n1,n2) dB((dO,n1,n2 ))
45 #define d3(n1,n2,n3) dB((dO,n1,n2,n3 ))
46 #define d4(n1,n2,n3,n4) dB((dO,n1,n2,n3,n4))
48 static const char version[]="This is MobilDock SMS sender (" PACKAGE " " VERSION ")\n";
56 static int dis_cleanup=0,devfd=-1;
58 static char *phone,*body,*device,*logname,*lockfile,*smsc,*maxretry,*readtime,*chartime,*cmdtime;
60 static long maxretryn=DEF_MAXRETRY,readtimen=DEF_READTIME,chartimen=DEF_CHARTIME,cmdtimen=DEF_CMDTIME;
61 static size_t bodylen;
63 static char *devicename; /* path stripped */
64 static char lockreal[512],locked;
66 static struct termios restios,tios;
67 static char restios_yes;
71 #ifndef PRINTF_WORKS_PM
74 const char *fmt,va_list ap)
84 if (gethostname(host,sizeof(host))) strcpy(host,"<ERROR>");
88 if ((s=strchr(ctm,'\n'))) *s='\0';
89 fprintf(logf,"%s %s %s[%d]: ",ctm,host,pname,mypid);
90 vfprintf(logf,fmt,ap);
91 #ifndef PRINTF_WORKS_PM
92 if (outerr) fputs(strerror(errno),logf);
98 static void logmsg(const char *fmt,...)
103 #ifndef PRINTF_WORKS_PM
110 static void error(const char *fmt,...)
114 #ifndef PRINTF_WORKS_PM
119 if (fatal=='!' || fatal=='.' || fatal=='\n') fmt++;
122 #ifndef PRINTF_WORKS_PM
123 if (!(nfmt=strdup(fmt))) return;
125 if ((pm=(fmtl>=2 && !strcmp(fmt+fmtl-2,"%m")))) nfmt[fmtl-2]='\0';
128 fprintf(stderr,"%s: ",pname);
131 #ifdef PRINTF_WORKS_PM
137 if (fatal=='!') vlogmsg(
138 #ifdef PRINTF_WORKS_PM
146 #ifndef PRINTF_WORKS_PM
148 fputs(strerror(errno),stderr);
153 if (fatal!='\n') fputc((fatal=='.'?'.':'!'),stderr);
155 if (fatal=='!') exit(EXIT_FAILURE);
158 static void chk(void *p)
161 error("!Virtual memory exhausted");
164 static void cleanup(void)
167 if (dis_cleanup) return;
169 if (tcsetattr(devfd,TCSANOW,&restios))
170 error("Error restoring termios for device: %m");
173 if (locked && *lockreal) {
174 d2("Removing lockfile \"%s\"\n",lockreal);
175 if (unlink(lockreal))
176 error("Error removing my device lockfile \"%s\": %m",lockreal);
183 static void usage(void)
189 Usage: " PACKAGE " [-c|--config <cfgfile>] [-d|--device <device>]\n\
191 [-l|--lockfile <lock>] [-s|--smsc <smsc #>] [-m|--maxretry <#>]\n\
192 [-r|--readtime <sec>] [-t|--chartime <msec>] [-T|--cmdtime <msec>]\n\
193 [-f|--file] [-v|--verbose] [-h|--help] [-V|--version]\n\
194 <dest. phone> <msg text|msg filename>\n\
196 -c, --config\tRead this additional config file\n\
197 \t\t(def. \"" CONFIG_MAIN "\" and \"$HOME" CONFIG_HOME "\")\n\
198 -d, --device\tMobilDock on this serial device (def. \"" DEF_DEVICE "\")\n\
199 -L, --log\tLog all important messages to this file (def. \"" DEF_LOGNAME "\")\n\
200 -l, --lockfile\tLock serial port by this file, \"%%s\" is basename of device\n\
202 -s, --smsc\tUse this SMS Center number (def. query from Siemens A1)\n\
203 -m, --maxretry\tMaximum retries of any command before giving up (def. %d)\n\
204 -r, --readtime\tSeconds for maximum wait time for response (def. %ds)\n\
205 -t, --chartime\tMilliseconds between each char on baud 19200 (def. %dms)\n\
206 -T, --cmdtime\tMilliseconds before each whole AT command (def. %dms)\n\
207 -f, --file\tRead contents of message from file instead\n\
208 -v, --verbose\tIncrease verbosity level, more \"-v\"s give more messages\n\
209 -h, --help\tPrint a summary of the options\n\
210 -V, --version\tPrint the version number\n\
211 \n",version,DEF_LOCKFILE,DEF_MAXRETRY,DEF_READTIME,DEF_CHARTIME,DEF_CMDTIME);
215 static const struct option longopts[]={
219 {"lockfile",1,0,'l'},
221 {"maxretry",1,0,'m'},
222 {"readtime",1,0,'r'},
223 {"chartime",1,0,'t'},
224 {"cmdtime" ,1,0,'T'},
226 {"verbose" ,0,0,'v'},
228 {"version" ,0,0,'V'}};
230 static void processargs(int argp,char **args,const char *from);
232 static char *cfgstack[MAXCFGLOOP];
233 static unsigned cfgstacki=0;
235 static void chkfclose(FILE *f,const char *fname)
238 error("Error closing \"%s\": %m",fname);
241 static void readfile(const char *fname,char quiet)
245 char *args[MAXCFGARGS],*d,*s,blank,quote;
249 static unsigned tot=0;
251 if (tot++>=MAXCFGNUM) {
252 if (tot==MAXCFGNUM+1) error("Too many config files to read, max is %d, break-out",MAXCFGNUM);
255 if (!(f=fopen(fname,"rt"))) {
256 if (!quiet) error("Can't open config file \"%s\" for r/o: %m",fname);
259 if (verbose>=2) error(".Reading config file \"%s\"",fname);
260 if (fseek(f,0,SEEK_END))
261 error("Error seeking to end of \"s\": %m",fname);
262 if ((size=ftell(f))<0)
263 size=0,error("Error measuring \"%s\": %m",fname);
265 error("File \"%s\" is too long, read only %ld bytes",fname,MAXCONFIG);
266 chk(buf=malloc((size?size:MAXCONFIG)+1));
268 got=fread(buf,1,(size?size:MAXCONFIG),f);
269 if (size && got!=size)
270 error("File \"%s\" read error, got only %u bytes of %ld",fname,got,size);
274 for (argp=1,d=s=buf,blank=1,quote=0;s<buf+got;s++) {
277 if (!quote && isspace(c)) {
281 if (verbose>=2) error("\nConfig \"%s\": arg#%d: %s",fname,argp-1,args[argp-1]);
286 if (argp>=NELEM(args)-1) {
287 error("Too many arguments in \"%s\", from offset %d ignored",fname,s-buf);
294 if (c=='\\') { *d++=*++s; continue; }
295 if (c=='"' || c=='\'') {
296 if (!quote ) { quote=c; continue; }
297 if ( quote==c) { quote=0; continue; }
303 processargs(argp,args,fname);
322 static void processargs(int argp,char **args,const char *from)
325 static unsigned seq=0;
329 optarg=NULL; optind=0; /* FIXME: Possible portability problem. */
330 while ((optc=getopt_long(argp,args,"c:d:L:l:s:m:r:t:T:fvhV",longopts,NULL))!=EOF) switch (optc) {
332 if (cfgstacki>=NELEM(cfgstack)) {
333 error("Looping (%d) during attempt to read config file \"%s\", break-out",NELEM(cfgstack),optind);
336 chk(cfgstack[cfgstacki++]=strdup(optarg));
338 case 'd': case 'L': case 'l': case 's': case 'm': case 'r': case 't': case 'T':
339 for (i=0;i<NELEM(optset);i++)
340 if (optset[i].c==optc) {
341 if (optset[i].stamp && optset[i].stamp!=seq) {
342 assert(!!*optset[i].var);
345 free(*optset[i].var);
346 chk(*optset[i].var=strdup(optarg));
350 assert(i<NELEM(optset));
359 fprintf(stderr,version);
363 error("\nLast getopt(3) error occured during parsing option %d from \"%s\"! Follows help:",optind-1,from);
367 if (!phone && optind<argp)
368 chk(phone=strdup(args[optind++]));
369 if (!body && optind<argp) {
373 for (i=optind,bodylen=argp-optind;i<argp;i++)
374 bodylen+=strlen(args[i]);
375 chk(body=malloc(bodylen));
376 for (d=body,i=optind;i<argp;i++) {
377 size_t l=strlen(args[i]);
381 assert(d<=body+bodylen);
383 assert(d==body+bodylen);
388 char *s=cfgstack[--cfgstacki];
390 assert(cfgstacki>=0);
393 assert(cfgstacki>=0 && cfgstacki<NELEM(cfgstack));
397 static const struct {
401 {&phone,"destination phone number"},
403 {&body ,"body text"},
404 {&device,"device for communication"},
407 static char **emptycheck[]={&logname,&smsc,&body};
409 static void lockclose(int fd)
412 error("Error closing lockfile \"%s\"",lockreal);
415 static inline void lockdevice(void)
425 if (fd!=-1) lockclose(fd);
427 if (delay) sleep(delay);
428 delay=DEVLOCK_PERIOD;
429 if (verbose>=3) error(".Checking the lockfile \"%s\"..",lockreal);
430 if ((fd=open(lockreal,O_RDONLY))==-1) break;
431 if ((got=read(fd,buf,sizeof(buf)-1))<=0) {
433 if (empty>=DEVLOCK_MAXEMPTY) {
434 error(".Lockfile \"%s\" is still not valid, removing it",lockreal);
440 assert(got<sizeof(buf));
442 if (sscanf(buf,"%d",&pid)!=1) goto isempty;
445 if (kill(pid,0) && errno!=ESRCH && errno!=EPERM)
446 error("Error during checking consciousness of PID %d: %m",pid);
447 if (errno!=ESRCH) continue;
448 error(".Lockfile \"%s\" is stale (PID %d), removing it",lockreal,pid);
451 if (unlink(lockreal))
452 error("Error removing foreign lockfile \"%s\": %m",lockreal);
456 if ((fd=open(lockreal,O_WRONLY|O_CREAT|O_EXCL,0644))==-1) {
457 if (errno==EEXIST) goto recheck;
458 error("!Error creating lockfile \"%s\": %m",lockreal);
461 got=VARPRINTF(buf,"%010d\n",getpid()); assert(got==11);
462 if (write(fd,buf,got)!=got)
463 error("!Error writing data to lockfile \"%s\": %m",lockreal);
467 static char wasalarm=0;
468 static void sigalarm(int signo)
470 signal(SIGALRM,(RETSIGTYPE (*)(int))sigalarm);
472 if (verbose>=1) error("Timed out");
475 static void blocking(char yes)
477 static char state=-1;
478 if (state==yes) return;
479 if (fcntl(devfd,F_SETFL,(yes?0:O_NONBLOCK)))
480 error("!fcntl() on device for %sblocking mode: %m",(yes?"":"non-"));
484 static const char *record;
485 static char *catchdata;
486 static size_t catchdatal,catchdatasiz;
488 static void catched(const char *end)
495 if ((p=memchr(record,'\n',end-record))) end=p;
496 if ((len=end-record)) {
497 if (catchdatal+len>catchdatasiz)
498 chk(catchdata=realloc(catchdata,
499 (catchdatasiz=MAX(LINE_MAX,(catchdatal+len)*2))));
500 memcpy(catchdata+catchdatal,record,len);
504 assert(catchdatal<=catchdatasiz);
507 static int retrycnt=0;
508 static void retrying(void)
510 if (++retrycnt>maxretryn) error("!Maximum command retry count (%d) exceeded",maxretryn);
511 if (verbose>=2) error(".Retrying phase, %d out of %d..",retrycnt,maxretryn);
514 static char *devcmd(const char *term,const char *catch,const char *send,...)
516 size_t l,bufl,terml,catchl,fragl,offs;
523 if (!term) term="\nOK\n";
524 if ((errout=(*send=='!'))) send++;
528 if (errout) return(NULL);
533 l=VARVPRINTF(buf,send,ap); bufl=l+1;
535 if (bufl>=sizeof(buf)-1) error("!Command too big (%d>%d)",bufl,sizeof(buf)-1);
536 if (verbose>=2) error(".devcmd(send=\"%s\",term=\"%s\",catch=\"%s\")",buf,term,catch);
537 buf[l]='\r'; buf[l+1]='\n';
538 for (offs=0,got=0;offs<bufl;offs++) {
540 usleep((offs?chartimen:cmdtimen)*1000);
541 if (!offs && tcflush(devfd,TCIOFLUSH))
542 error("Error flushing I/O queue of device: %m");
543 if (write(devfd,buf+offs,1)!=1) break;
546 error("Error forcing output of char %d of cmd \"%s\": %m",offs,buf);
550 error("Wrote only %d of %d bytes of command: %m",got,bufl);
554 if (!(terml=strlen(term))) {
559 catchl=strlen(catch);
560 fragl=MAX(terml,catchl);
563 fragl=MAX(fragl,MAX(strlen(ERROR_SUBSTR1),strlen(ERROR_SUBSTR2)));
571 got=read(devfd,buf+bufl,sizeof(buf)-1-bufl);
572 if (got==-1 && errno==EAGAIN) {
575 got=read(devfd,buf+bufl,1);
578 if (wasalarm) error("!Maximum response timeout (%ds) exceeded",readtimen);
579 error("Couldn't read device data (ret=%d): %m",got);
584 /* FIXME: '\0' conversion */
585 while (buf+bufl>s && (s=memchr(s,'\r',buf+bufl-s))) *s='\n';
586 catched(buf+bufl); assert(!record || record==buf+bufl);
587 assert(bufl<sizeof(buf));
590 assert(strlen(buf)==bufl);
591 /* d3(">%s|%s<\n",buf,term); */
592 if (strstr(buf,ERROR_SUBSTR1) || strstr(buf,ERROR_SUBSTR2)) {
593 error("Found ERROR response on command \"%s\"",send);
596 if (catch && bufl>=catchl && (hit=strstr(buf,catch))) {
598 catched(buf+bufl); assert(!record || record==buf+bufl);
600 if ( bufl>= terml && (hit=strstr(buf,term))) break;
601 memmove(buf,buf+bufl-(fragl-1),fragl-1);
603 if (record) record=buf+bufl;
608 if (!catch) return(NULL);
609 error("Data requested on command \"%s\" but no found after term \"%s\"",send,term);
616 if (verbose>=2) error(".Returning data \"%s\" for cmd \"%s\"",catchdata,send);
620 static int prepaddr(unsigned char *d,const char *addr)
626 if ((plus=(*addr=='+'))) addr++;
627 *++d=(plus?ADDR_INT:ADDR_NAT);
629 if (*addr<'0' || *addr>'9')
630 error("!Error during conversion of number at: %s",addr);
633 if ((flip=!flip)) *++d=0xF0|n;
634 else *d=(*d&0x0F)|(n<<4U);
639 static char *finalsmsc;
640 #define SMSCBINSIZE (1+1+(MAXNUMLEN+1)/2)
641 static char pdusmsc[SMSCBINSIZE*2+1];
643 static inline char tohex(unsigned char x)
646 if (x<10) return(x +'0');
650 static void textconv(char *d,unsigned char *s,size_t len)
660 static inline void smscset(void)
664 unsigned char bin[2+(MAXNUMLEN+1)/2];
666 if (smsc) devcmd(NULL,NULL,"\r\nAT+CSCA=\"%s\"",smsc);
667 s=devcmd(NULL,"\n+CSCA:","\r\nAT+CSCA?");
668 while (isspace(*s)) s++;
669 if (!*s || !strcmp(s,"EMPTY"))
670 error("!No SMS set in A1 found");
671 if (verbose>=1) error("\nFound default SMSC in A1: %s",s);
672 if (*s!='"') error("!No left-quote found in: %s",s);
673 if (!(t=strrchr(s+1,'"'))) error("!No right-quote found in: %s",s);
675 while (isspace(*t)) t++;
676 if (*t++!=',') error("!No comma found after quotes in: %s",s);
677 while (isspace(*t)) t++;
678 l=strtol(t,&serr,10);
679 if ((l!=ADDR_NAT && l!=ADDR_INT) || (serr && *serr))
680 error("!Type parse error in: %s",s);
681 if (l==ADDR_NAT || s[1]=='+') s++;
684 chk(finalsmsc=strdup(s));
685 if (verbose>=2) error("\nDecoded SMSC address: %s",finalsmsc);
686 bin[0]=1+(prepaddr(bin,finalsmsc)+1)/2;
687 textconv(pdusmsc,bin,bin[0]+1);
690 static char *pdudata;
692 static inline unsigned char charconv(char c,size_t offs)
702 if ((c>='A' && c<='Z') || (c>='a' && c<='z') || (c>='0' && c<='9')) return(c);
703 error("Can't convert character '%c' (0x%02X) at offs %d (0-based), substituted '?'",
704 c,(unsigned char)c,offs);
709 static inline void genpdu(void)
711 static unsigned char pdu[64+MAXNUMLEN/2+(MAXBODYLEN*7)/8];
712 unsigned char *d=pdu;
714 char inb=0,outb=0,xb;
721 *d=i; d+=1+1+(i+1)/2;
725 if (bodylen>MAXBODYLEN) {
726 error("Body too large (%d>%d), cut",bodylen,MAXBODYLEN);
730 assert(d<pdu+sizeof(pdu));
731 while (bodylen || inb) {
733 assert(bodylen>0); assert(!!*body);
734 inreg=charconv(*body++,offs++);
743 d4("inb=%d,outb=%d,xb=%d\n",inb,outb,xb);
744 *d|=((inreg>>(unsigned)(7-inb))&((1<<xb)-1))<<(unsigned)(8-outb);
748 assert(d<pdu+sizeof(pdu));
749 pdudata=malloc(2*(d-pdu)+1);
750 textconv(pdudata,pdu,d-pdu);
756 const char *const msg;
758 { &maxretry,&maxretryn,"maxretry" },
759 { &readtime,&readtimen,"readtime" },
760 { &chartime,&chartimen,"chartime" },
761 { &cmdtime ,&cmdtimen ,"cmdtime" },
764 int main(int argc,char **argv)
771 if ((s=strrchr((pname=*argv),'/'))) pname=s+1;
773 signal(SIGTERM,(RETSIGTYPE (*)(int))cleanup);
774 signal(SIGQUIT,(RETSIGTYPE (*)(int))cleanup);
775 signal(SIGINT ,(RETSIGTYPE (*)(int))cleanup);
776 signal(SIGHUP ,(RETSIGTYPE (*)(int))cleanup);
777 processargs(argc,argv,"<command-line>");
778 if ((s=getenv("HOME"))) {
780 char *buf=malloc(l+50);
783 strcpy(buf+l,CONFIG_HOME);
787 readfile(CONFIG_MAIN,1);
789 for (i=0;i<NELEM(nullcheck);i++)
790 if (!*nullcheck[i].var) {
791 error("Missing parameter \"%s\"",nullcheck[i].name);
794 if (fatal) error("!Previous error%s considered unrecoverable",(fatal==1?"":"s"));
795 for (i=0;i<NELEM(emptycheck);i++)
796 if (*emptycheck[i] && !**emptycheck[i]) {
797 free(*emptycheck[i]);
800 if (!logname) logname=DEF_LOGNAME;
801 if (!lockfile) lockfile=DEF_LOCKFILE;
802 if (!device) device=DEF_DEVICE;
803 if (body && readbody) {
815 error("\nPlease enter the SMS text body, end with EOF (ctrl-D):");
818 if (!(fin=fopen(finame,"rt")))
819 error("!Can't open data file \"%s\" for r/o: %m",finame);
821 chk(body=malloc(BODYLOAD));
822 bodylen=fread(body,1,BODYLOAD,fin);
824 error("!Error reading stream \"%s\": %m",(finame?finame:"<stdin>"));
826 chkfclose(fin,finame);
831 for (i=0;i<NELEM(numarg);i++) {
833 if (!*numarg[i].sp) continue;
834 *numarg[i].ip=strtol(*numarg[i].sp,&serr,0);
835 if (*numarg[i].ip<0 || *numarg[i].ip>=LONG_MAX || !serr || *serr)
836 error("!Number parse error for parameter \"%s\" of \"%s\" at: %s",
837 numarg[i].msg,*numarg[i].sp,serr);
840 if (!strchr(device,'/')) {
841 size_t l=strlen(device);
842 chk(s=malloc(5+l+1));
848 devicename=strrchr(device,'/')+1; assert(!!(devicename-1));
849 for (i=0,s=lockfile;*s;s++) {
850 if (*s!='%') continue;
852 if (*s=='%') continue;
854 if (i) error("!Only one \"%%s\" permitted in lockfile format-string");
857 error("!Invalid format-character '%c' in lockfile format-string, only \"%%s\" allowed",*s);
861 if (!(logf=fopen(logname,"a")))
862 error("!Error opening log \"%s\" for append: %m",logname);
863 logmsg("Starting up: " PACKAGE " " VERSION);
867 if (lockfile && *lockfile && VARPRINTF(lockreal,lockfile,devicename)>0) {
869 if (verbose>=1) error(".Locking device \"%s\" by \"%s\"..",device,lockreal);
873 if ((end-=start)>LOCKREPORT)
874 logmsg("Device lock succeeded after %d seconds",end);
876 if (verbose>=1) error(".Opening device \"%s\"..",device);
877 if ((devfd=open(device,O_RDWR|O_NDELAY))<0)
878 error("!Cannot open device \"%s\" for rw-access: %m",device);
880 if (tcgetattr(devfd,&restios))
881 error("Unable to get termios settings: %m");
883 restios.c_cflag=(restios.c_cflag&~(CBAUD|CBAUDEX))|B0|HUPCL;
886 tios.c_iflag=IGNBRK|IGNPAR|IXON|IXOFF;
888 tios.c_cflag=CS8|CREAD|CLOCAL|B19200|HUPCL;
889 tios.c_lflag=IEXTEN|NOFLSH;
890 memset(tios.c_cc,_POSIX_VDISABLE,sizeof(tios.c_cc));
893 cfsetispeed(&tios,B19200);
894 if (cfsetospeed(&tios,B19200)|cfsetispeed(&tios,B19200))
895 error("Error setting termios baudrate on device: %m");
896 if (tcflush(devfd,TCIOFLUSH))
897 error("Error flushing termios (TCIOFLUSH) on device: %m");
898 if (tcsetattr(devfd,TCSANOW,&tios))
899 error("!Unable to set initial termios device settings: %m");
901 signal(SIGALRM,(RETSIGTYPE (*)(int))sigalarm);
903 devcmd("",NULL,"\r\nAT\032");
904 devcmd(NULL,NULL,"\r\nAT");
906 devcmd(NULL,NULL,"\r\nAT+CMGF=0");
907 devcmd("\n> ",NULL,"\r\nAT+CMGS=%d",(strlen(pdusmsc)+strlen(pdudata))/2);
908 if (!(s=devcmd(NULL,"\n+CMGS:","!%s%s\032",pdusmsc,pdudata))) retrying();
910 while (isspace(*s)) s++;
911 if (verbose>=1) error("\nMessage successfuly sent with MR: %s",s);
912 devcmd(NULL,NULL,"\r\nAT");
914 logmsg("SMS sent (after %d retries), message reference: %s",retrycnt,s);
915 return(EXIT_SUCCESS);