3 static char rcsid[] ATTR_UNUSED = "$Id$";
19 #include <sys/types.h>
26 #ifdef HAVE_GETOPT_LONG
33 char *strdup(const char *s);
34 int kill(pid_t pid,int sig);
35 int snprintf(char *str,size_t n,const char *format,...);
36 int vsnprintf(char *str,size_t n,const char *format,va_list ap);
37 void usleep(unsigned long usec);
40 #define NELEM(x) (sizeof((x))/sizeof(*(x)))
47 /* ANSI C does not allow macro with variable arguments */
49 #define dB(a) dbg(fprintf a)
51 #define d1(n1) dB((dO,n1 ))
52 #define d2(n1,n2) dB((dO,n1,n2 ))
53 #define d3(n1,n2,n3) dB((dO,n1,n2,n3 ))
54 #define d4(n1,n2,n3,n4) dB((dO,n1,n2,n3,n4))
56 static const char version[]="This is MobilDock SMS sender (" PACKAGE " " VERSION ")\n";
64 static int dis_cleanup=0,devfd=-1;
66 static char *phone,*body,*device,*logname,*lockfile,*smsc,*maxretry,*readtime,*chartime,*cmdtime;
68 static long maxretryn=DEF_MAXRETRY,readtimen=DEF_READTIME,chartimen=DEF_CHARTIME,cmdtimen=DEF_CMDTIME;
69 static size_t bodylen;
71 static char *devicename; /* path stripped */
72 static char lockreal[512],locked;
74 static struct termios restios,tios;
75 static char restios_yes;
79 #ifndef PRINTF_WORKS_PM
82 const char *fmt,va_list ap)
92 if (gethostname(host,sizeof(host))) strcpy(host,"<ERROR>");
96 if ((s=strchr(ctm,'\n'))) *s='\0';
97 fprintf(logf,"%s %s %s[%d]: ",ctm,host,pname,mypid);
98 vfprintf(logf,fmt,ap);
99 #ifndef PRINTF_WORKS_PM
100 if (outerr) fputs(strerror(errno),logf);
106 static void logmsg(const char *fmt,...)
111 #ifndef PRINTF_WORKS_PM
118 static void error(const char *fmt,...)
122 #ifndef PRINTF_WORKS_PM
127 if (fatal=='!' || fatal=='.' || fatal=='\n') fmt++;
130 #ifndef PRINTF_WORKS_PM
131 if (!(nfmt=strdup(fmt))) return;
133 if ((pm=(fmtl>=2 && !strcmp(fmt+fmtl-2,"%m")))) nfmt[fmtl-2]='\0';
136 fprintf(stderr,"%s: ",pname);
139 #ifdef PRINTF_WORKS_PM
145 if (fatal=='!') vlogmsg(
146 #ifdef PRINTF_WORKS_PM
154 #ifndef PRINTF_WORKS_PM
156 fputs(strerror(errno),stderr);
161 if (fatal!='\n') fputc((fatal=='.'?'.':'!'),stderr);
163 if (fatal=='!') exit(EXIT_FAILURE);
166 static void chk(void *p)
169 error("!Virtual memory exhausted");
172 static void cleanup(void)
175 if (dis_cleanup) return;
177 if (tcsetattr(devfd,TCSANOW,&restios))
178 error("Error restoring termios for device: %m");
181 if (locked && *lockreal) {
182 d2("Removing lockfile \"%s\"\n",lockreal);
183 if (unlink(lockreal))
184 error("Error removing my device lockfile \"%s\": %m",lockreal);
191 static void usage(void)
197 Usage: " PACKAGE " [-c|--config <cfgfile>] [-d|--device <device>]\n\
199 [-l|--lockfile <lock>] [-s|--smsc <smsc #>] [-m|--maxretry <#>]\n\
200 [-r|--readtime <sec>] [-t|--chartime <msec>] [-T|--cmdtime <msec>]\n\
201 [-f|--file] [-v|--verbose] [-h|--help] [-V|--version]\n\
202 <dest. phone> <msg text|msg filename>\n\
204 -c, --config\tRead this additional config file\n\
205 \t\t(def. \"" CONFIG_MAIN "\" and \"$HOME" CONFIG_HOME "\")\n\
206 -d, --device\tMobilDock on this serial device (def. \"" DEF_DEVICE "\")\n\
207 -L, --log\tLog all important messages to this file (def. \"" DEF_LOGNAME "\")\n\
208 -l, --lockfile\tLock serial port by this file, \"%%s\" is basename of device\n\
210 -s, --smsc\tUse this SMS Center number (def. query from Siemens A1)\n\
211 -m, --maxretry\tMaximum retries of any command before giving up (def. %d)\n\
212 -r, --readtime\tSeconds for maximum wait time for response (def. %ds)\n\
213 -t, --chartime\tMilliseconds between each char on baud 19200 (def. %dms)\n\
214 -T, --cmdtime\tMilliseconds before each whole AT command (def. %dms)\n\
215 -f, --file\tRead contents of message from file instead\n\
216 -v, --verbose\tIncrease verbosity level, more \"-v\"s give more messages\n\
217 -h, --help\tPrint a summary of the options\n\
218 -V, --version\tPrint the version number\n\
219 \n",version,DEF_LOCKFILE,DEF_MAXRETRY,DEF_READTIME,DEF_CHARTIME,DEF_CMDTIME);
223 static const struct option longopts[]={
227 {"lockfile",1,0,'l'},
229 {"maxretry",1,0,'m'},
230 {"readtime",1,0,'r'},
231 {"chartime",1,0,'t'},
232 {"cmdtime" ,1,0,'T'},
234 {"verbose" ,0,0,'v'},
236 {"version" ,0,0,'V'}};
238 static void processargs(int argp,char **args,const char *from);
240 static char *cfgstack[MAXCFGLOOP];
241 static unsigned cfgstacki=0;
243 static void chkfclose(FILE *f,const char *fname)
246 error("Error closing \"%s\": %m",fname);
249 static void readfile(const char *fname,char quiet)
253 char *args[MAXCFGARGS],*d,*s,blank,quote;
257 static unsigned tot=0;
259 if (tot++>=MAXCFGNUM) {
260 if (tot==MAXCFGNUM+1) error("Too many config files to read, max is %d, break-out",MAXCFGNUM);
263 if (!(f=fopen(fname,"rt"))) {
264 if (!quiet) error("Can't open config file \"%s\" for r/o: %m",fname);
267 if (verbose>=2) error(".Reading config file \"%s\"",fname);
268 if (fseek(f,0,SEEK_END))
269 error("Error seeking to end of \"s\": %m",fname);
270 if ((size=ftell(f))<0)
271 size=0,error("Error measuring \"%s\": %m",fname);
273 error("File \"%s\" is too long, read only %ld bytes",fname,MAXCONFIG);
274 chk(buf=malloc((size?size:MAXCONFIG)+1));
276 got=fread(buf,1,(size?size:MAXCONFIG),f);
277 if (size && got!=size)
278 error("File \"%s\" read error, got only %u bytes of %ld",fname,got,size);
282 for (argp=1,d=s=buf,blank=1,quote=0;s<buf+got;s++) {
285 if (!quote && isspace(c)) {
289 if (verbose>=2) error("\nConfig \"%s\": arg#%d: %s",fname,argp-1,args[argp-1]);
294 if (argp>=NELEM(args)-1) {
295 error("Too many arguments in \"%s\", from offset %d ignored",fname,s-buf);
302 if (c=='\\') { *d++=*++s; continue; }
303 if (c=='"' || c=='\'') {
304 if (!quote ) { quote=c; continue; }
305 if ( quote==c) { quote=0; continue; }
311 processargs(argp,args,fname);
330 static void processargs(int argp,char **args,const char *from)
333 static unsigned seq=0;
337 optarg=NULL; optind=0; /* FIXME: Possible portability problem. */
338 while ((optc=getopt_long(argp,args,"c:d:L:l:s:m:r:t:T:fvhV",longopts,NULL))!=EOF) switch (optc) {
340 if (cfgstacki>=NELEM(cfgstack)) {
341 error("Looping (%d) during attempt to read config file \"%s\", break-out",NELEM(cfgstack),optind);
344 chk(cfgstack[cfgstacki++]=strdup(optarg));
346 case 'd': case 'L': case 'l': case 's': case 'm': case 'r': case 't': case 'T':
347 for (i=0;i<NELEM(optset);i++)
348 if (optset[i].c==optc) {
349 if (optset[i].stamp && optset[i].stamp!=seq) {
350 assert(!!*optset[i].var);
353 free(*optset[i].var);
354 chk(*optset[i].var=strdup(optarg));
358 assert(i<NELEM(optset));
367 fprintf(stderr,version);
371 error("\nLast getopt(3) error occured during parsing option %d from \"%s\"! Follows help:",optind-1,from);
375 if (!phone && optind<argp)
376 chk(phone=strdup(args[optind++]));
377 if (!body && optind<argp) {
381 for (i=optind,bodylen=argp-optind;i<argp;i++)
382 bodylen+=strlen(args[i]);
383 chk(body=malloc(bodylen));
384 for (d=body,i=optind;i<argp;i++) {
385 size_t l=strlen(args[i]);
389 assert(d<=body+bodylen);
391 assert(d==body+bodylen);
396 char *s=cfgstack[--cfgstacki];
398 assert(cfgstacki>=0);
401 assert(cfgstacki>=0 && cfgstacki<NELEM(cfgstack));
405 static const struct {
409 {&phone,"destination phone number"},
411 {&body ,"body text"},
412 {&device,"device for communication"},
415 static char **emptycheck[]={&logname,&smsc,&body};
417 static void lockclose(int fd)
420 error("Error closing lockfile \"%s\"",lockreal);
423 static inline void lockdevice(void)
433 if (fd!=-1) lockclose(fd);
435 if (delay) sleep(delay);
436 delay=DEVLOCK_PERIOD;
437 if (verbose>=3) error(".Checking the lockfile \"%s\"..",lockreal);
438 if ((fd=open(lockreal,O_RDONLY))==-1) break;
439 if ((got=read(fd,buf,sizeof(buf)-1))<=0) {
441 if (empty>=DEVLOCK_MAXEMPTY) {
442 error(".Lockfile \"%s\" is still not valid, removing it",lockreal);
448 assert(got<sizeof(buf));
450 if (sscanf(buf,"%d",&pid)!=1) goto isempty;
453 if (kill(pid,0) && errno!=ESRCH && errno!=EPERM)
454 error("Error during checking consciousness of PID %d: %m",pid);
455 if (errno!=ESRCH) continue;
456 error(".Lockfile \"%s\" is stale (PID %d), removing it",lockreal,pid);
459 if (unlink(lockreal))
460 error("Error removing foreign lockfile \"%s\": %m",lockreal);
464 if ((fd=open(lockreal,O_WRONLY|O_CREAT|O_EXCL,0644))==-1) {
465 if (errno==EEXIST) goto recheck;
466 error("!Error creating lockfile \"%s\": %m",lockreal);
469 got=VARPRINTF(buf,"%010d\n",getpid()); assert(got==11);
470 if (write(fd,buf,got)!=got)
471 error("!Error writing data to lockfile \"%s\": %m",lockreal);
475 static char wasalarm=0;
476 static void sigalarm(int signo)
478 signal(SIGALRM,(RETSIGTYPE (*)(int))sigalarm);
480 if (verbose>=1) error("Timed out");
483 static void blocking(char yes)
485 static char state=-1;
486 if (state==yes) return;
487 if (fcntl(devfd,F_SETFL,(yes?0:O_NONBLOCK)))
488 error("!fcntl() on device for %sblocking mode: %m",(yes?"":"non-"));
492 static const char *record;
493 static char *catchdata;
494 static size_t catchdatal,catchdatasiz;
496 static void catched(const char *end)
503 if ((p=memchr(record,'\n',end-record))) end=p;
504 if ((len=end-record)) {
505 if (catchdatal+len>catchdatasiz)
506 chk(catchdata=realloc(catchdata,
507 (catchdatasiz=MAX(LINE_MAX,(catchdatal+len)*2))));
508 memcpy(catchdata+catchdatal,record,len);
512 assert(catchdatal<=catchdatasiz);
515 static int retrycnt=0;
516 static void retrying(void)
518 if (++retrycnt>maxretryn) error("!Maximum command retry count (%d) exceeded",maxretryn);
519 if (verbose>=2) error(".Retrying phase, %d out of %d..",retrycnt,maxretryn);
522 static char *devcmd(const char *term,const char *catch,const char *send,...)
524 size_t l,bufl,terml,catchl,fragl,offs;
531 if (!term) term="\nOK\n";
532 if ((errout=(*send=='!'))) send++;
536 if (errout) return(NULL);
541 l=VARVPRINTF(buf,send,ap); bufl=l+1;
543 if (bufl>=sizeof(buf)-1) error("!Command too big (%d>%d)",bufl,sizeof(buf)-1);
544 if (verbose>=2) error(".devcmd(send=\"%s\",term=\"%s\",catch=\"%s\")",buf,term,catch);
545 buf[l]='\r'; buf[l+1]='\n';
546 for (offs=0,got=0;offs<bufl;offs++) {
548 usleep((offs?chartimen:cmdtimen)*1000);
549 if (!offs && tcflush(devfd,TCIOFLUSH))
550 error("Error flushing I/O queue of device: %m");
551 if (write(devfd,buf+offs,1)!=1) break;
554 error("Error forcing output of char %d of cmd \"%s\": %m",offs,buf);
558 error("Wrote only %d of %d bytes of command: %m",got,bufl);
562 if (!(terml=strlen(term))) {
567 catchl=strlen(catch);
568 fragl=MAX(terml,catchl);
571 fragl=MAX(fragl,MAX(strlen(ERROR_SUBSTR1),strlen(ERROR_SUBSTR2)));
579 got=read(devfd,buf+bufl,sizeof(buf)-1-bufl);
580 if (got==-1 && errno==EAGAIN) {
583 got=read(devfd,buf+bufl,1);
586 if (wasalarm) error("!Maximum response timeout (%ds) exceeded",readtimen);
587 error("Couldn't read device data (ret=%d): %m",got);
592 /* FIXME: '\0' conversion */
593 while (buf+bufl>s && (s=memchr(s,'\r',buf+bufl-s))) *s='\n';
594 catched(buf+bufl); assert(!record || record==buf+bufl);
595 assert(bufl<sizeof(buf));
598 assert(strlen(buf)==bufl);
599 /* d3(">%s|%s<\n",buf,term); */
600 if (strstr(buf,ERROR_SUBSTR1) || strstr(buf,ERROR_SUBSTR2)) {
601 error("Found ERROR response on command \"%s\"",send);
604 if (catch && bufl>=catchl && (hit=strstr(buf,catch))) {
606 catched(buf+bufl); assert(!record || record==buf+bufl);
608 if ( bufl>= terml && (hit=strstr(buf,term))) break;
609 memmove(buf,buf+bufl-(fragl-1),fragl-1);
611 if (record) record=buf+bufl;
616 if (!catch) return(NULL);
617 error("Data requested on command \"%s\" but no found after term \"%s\"",send,term);
624 if (verbose>=2) error(".Returning data \"%s\" for cmd \"%s\"",catchdata,send);
628 static int prepaddr(unsigned char *d,const char *addr)
634 if ((plus=(*addr=='+'))) addr++;
635 *++d=(plus?ADDR_INT:ADDR_NAT);
637 if (*addr<'0' || *addr>'9')
638 error("!Error during conversion of number at: %s",addr);
641 if ((flip=!flip)) *++d=0xF0|n;
642 else *d=(*d&0x0F)|(n<<4U);
647 static char *finalsmsc;
648 #define SMSCBINSIZE (1+1+(MAXNUMLEN+1)/2)
649 static char pdusmsc[SMSCBINSIZE*2+1];
651 static inline char tohex(unsigned char x)
654 if (x<10) return(x +'0');
658 static void textconv(char *d,unsigned char *s,size_t len)
668 static inline void smscset(void)
672 unsigned char bin[2+(MAXNUMLEN+1)/2];
674 if (smsc) devcmd(NULL,NULL,"\r\nAT+CSCA=\"%s\"",smsc);
675 s=devcmd(NULL,"\n+CSCA:","\r\nAT+CSCA?");
676 while (isspace(*s)) s++;
677 if (!*s || !strcmp(s,"EMPTY"))
678 error("!No SMS set in A1 found");
679 if (verbose>=1) error("\nFound default SMSC in A1: %s",s);
680 if (*s!='"') error("!No left-quote found in: %s",s);
681 if (!(t=strrchr(s+1,'"'))) error("!No right-quote found in: %s",s);
683 while (isspace(*t)) t++;
684 if (*t++!=',') error("!No comma found after quotes in: %s",s);
685 while (isspace(*t)) t++;
686 l=strtol(t,&serr,10);
687 if ((l!=ADDR_NAT && l!=ADDR_INT) || (serr && *serr))
688 error("!Type parse error in: %s",s);
689 if (l==ADDR_NAT || s[1]=='+') s++;
692 chk(finalsmsc=strdup(s));
693 if (verbose>=2) error("\nDecoded SMSC address: %s",finalsmsc);
694 bin[0]=1+(prepaddr(bin,finalsmsc)+1)/2;
695 textconv(pdusmsc,bin,bin[0]+1);
698 static char *pdudata;
700 static inline unsigned char charconv(char c,size_t offs)
710 if ((c>='A' && c<='Z') || (c>='a' && c<='z') || (c>='0' && c<='9')) return(c);
711 error("Can't convert character '%c' (0x%02X) at offs %d (0-based), substituted '?'",
712 c,(unsigned char)c,offs);
717 static inline void genpdu(void)
719 static unsigned char pdu[64+MAXNUMLEN/2+(MAXBODYLEN*7)/8];
720 unsigned char *d=pdu;
722 char inb=0,outb=0,xb;
729 *d=i; d+=1+1+(i+1)/2;
733 if (bodylen>MAXBODYLEN) {
734 error("Body too large (%d>%d), cut",bodylen,MAXBODYLEN);
738 assert(d<pdu+sizeof(pdu));
739 while (bodylen || inb) {
741 assert(bodylen>0); assert(!!*body);
742 inreg=charconv(*body++,offs++);
751 d4("inb=%d,outb=%d,xb=%d\n",inb,outb,xb);
752 *d|=((inreg>>(unsigned)(7-inb))&((1<<xb)-1))<<(unsigned)(8-outb);
756 assert(d<pdu+sizeof(pdu));
757 pdudata=malloc(2*(d-pdu)+1);
758 textconv(pdudata,pdu,d-pdu);
764 const char *const msg;
766 { &maxretry,&maxretryn,"maxretry" },
767 { &readtime,&readtimen,"readtime" },
768 { &chartime,&chartimen,"chartime" },
769 { &cmdtime ,&cmdtimen ,"cmdtime" },
772 int main(int argc,char **argv)
779 if ((s=strrchr((pname=*argv),'/'))) pname=s+1;
781 signal(SIGTERM,(RETSIGTYPE (*)(int))cleanup);
782 signal(SIGQUIT,(RETSIGTYPE (*)(int))cleanup);
783 signal(SIGINT ,(RETSIGTYPE (*)(int))cleanup);
784 signal(SIGHUP ,(RETSIGTYPE (*)(int))cleanup);
785 processargs(argc,argv,"<command-line>");
786 if ((s=getenv("HOME"))) {
788 char *buf=malloc(l+50);
791 strcpy(buf+l,CONFIG_HOME);
795 readfile(CONFIG_MAIN,1);
797 for (i=0;i<NELEM(nullcheck);i++)
798 if (!*nullcheck[i].var) {
799 error("Missing parameter \"%s\"",nullcheck[i].name);
802 if (fatal) error("!Previous error%s considered unrecoverable",(fatal==1?"":"s"));
803 for (i=0;i<NELEM(emptycheck);i++)
804 if (*emptycheck[i] && !**emptycheck[i]) {
805 free(*emptycheck[i]);
808 if (!logname) logname=DEF_LOGNAME;
809 if (!lockfile) lockfile=DEF_LOCKFILE;
810 if (!device) device=DEF_DEVICE;
811 if (body && readbody) {
823 error("\nPlease enter the SMS text body, end with EOF (ctrl-D):");
826 if (!(fin=fopen(finame,"rt")))
827 error("!Can't open data file \"%s\" for r/o: %m",finame);
829 chk(body=malloc(BODYLOAD));
830 bodylen=fread(body,1,BODYLOAD,fin);
832 error("!Error reading stream \"%s\": %m",(finame?finame:"<stdin>"));
834 chkfclose(fin,finame);
839 for (i=0;i<NELEM(numarg);i++) {
841 if (!*numarg[i].sp) continue;
842 *numarg[i].ip=strtol(*numarg[i].sp,&serr,0);
843 if (*numarg[i].ip<0 || *numarg[i].ip>=LONG_MAX || !serr || *serr)
844 error("!Number parse error for parameter \"%s\" of \"%s\" at: %s",
845 numarg[i].msg,*numarg[i].sp,serr);
848 if (!strchr(device,'/')) {
849 size_t l=strlen(device);
850 chk(s=malloc(5+l+1));
856 devicename=strrchr(device,'/')+1; assert(!!(devicename-1));
857 for (i=0,s=lockfile;*s;s++) {
858 if (*s!='%') continue;
860 if (*s=='%') continue;
862 if (i) error("!Only one \"%%s\" permitted in lockfile format-string");
865 error("!Invalid format-character '%c' in lockfile format-string, only \"%%s\" allowed",*s);
869 if (!(logf=fopen(logname,"a")))
870 error("!Error opening log \"%s\" for append: %m",logname);
871 logmsg("Starting up: " PACKAGE " " VERSION);
875 if (lockfile && *lockfile && VARPRINTF(lockreal,lockfile,devicename)>0) {
877 if (verbose>=1) error(".Locking device \"%s\" by \"%s\"..",device,lockreal);
881 if ((end-=start)>LOCKREPORT)
882 logmsg("Device lock succeeded after %d seconds",end);
884 if (verbose>=1) error(".Opening device \"%s\"..",device);
885 if ((devfd=open(device,O_RDWR|O_NDELAY))<0)
886 error("!Cannot open device \"%s\" for rw-access: %m",device);
888 if (tcgetattr(devfd,&restios))
889 error("Unable to get termios settings: %m");
891 restios.c_cflag=(restios.c_cflag&~(CBAUD|CBAUDEX))|B0|HUPCL;
894 tios.c_iflag=IGNBRK|IGNPAR|IXON|IXOFF;
896 tios.c_cflag=CS8|CREAD|CLOCAL|B19200|HUPCL;
897 tios.c_lflag=IEXTEN|NOFLSH;
898 memset(tios.c_cc,_POSIX_VDISABLE,sizeof(tios.c_cc));
901 cfsetispeed(&tios,B19200);
902 if (cfsetospeed(&tios,B19200)|cfsetispeed(&tios,B19200))
903 error("Error setting termios baudrate on device: %m");
904 if (tcflush(devfd,TCIOFLUSH))
905 error("Error flushing termios (TCIOFLUSH) on device: %m");
906 if (tcsetattr(devfd,TCSANOW,&tios))
907 error("!Unable to set initial termios device settings: %m");
909 signal(SIGALRM,(RETSIGTYPE (*)(int))sigalarm);
911 devcmd("",NULL,"\r\nAT\032");
912 devcmd(NULL,NULL,"\r\nAT");
914 devcmd(NULL,NULL,"\r\nAT+CMGF=0");
915 devcmd("\n> ",NULL,"\r\nAT+CMGS=%d",(strlen(pdusmsc)+strlen(pdudata))/2);
916 if (!(s=devcmd(NULL,"\n+CMGS:","!%s%s\032",pdusmsc,pdudata))) retrying();
918 while (isspace(*s)) s++;
919 if (verbose>=1) error("\nMessage successfuly sent with MR: %s",s);
920 devcmd(NULL,NULL,"\r\nAT");
922 logmsg("SMS sent (after %d retries), message reference: %s",retrycnt,s);
923 return(EXIT_SUCCESS);