3 static char rcsid[] ATTR_UNUSED = "$Id$";
8 * Revision 1.4 1999/07/14 01:01:11 short
9 * Termios made compatible with Digital UNIX 4.0, cfset[io]speed() missing.
11 * Revision 1.3 1999/06/03 11:46:41 short
12 * Logging (--log) implemented.
14 * Revision 1.2 1999/06/03 10:38:52 short
15 * Implemented remaining communication timeouts and maximum retry count.
17 * Revision 1.1.1.1 1999/05/26 13:06:26 short
18 * First alpha release.
35 #include <sys/types.h>
42 #ifdef HAVE_GETOPT_LONG
49 char *strdup(const char *s);
50 int kill(pid_t pid,int sig);
51 int snprintf(char *str,size_t n,const char *format,...);
52 int vsnprintf(char *str,size_t n,const char *format,va_list ap);
53 void usleep(unsigned long usec);
56 #define NELEM(x) (sizeof((x))/sizeof(*(x)))
63 /* ANSI C does not allow macro with variable arguments */
65 #define dB(a) dbg(fprintf a)
67 #define d1(n1) dB((dO,n1 ))
68 #define d2(n1,n2) dB((dO,n1,n2 ))
69 #define d3(n1,n2,n3) dB((dO,n1,n2,n3 ))
70 #define d4(n1,n2,n3,n4) dB((dO,n1,n2,n3,n4))
72 static const char version[]="This is MobilDock SMS sender (" PACKAGE " " VERSION ")\n";
80 static int dis_cleanup=0,devfd=-1;
82 static char *phone,*body,*device,*logname,*lockfile,*smsc,*maxretry,*readtime,*chartime,*cmdtime;
84 static long maxretryn=DEF_MAXRETRY,readtimen=DEF_READTIME,chartimen=DEF_CHARTIME,cmdtimen=DEF_CMDTIME;
85 static size_t bodylen;
87 static char *devicename; /* path stripped */
88 static char lockreal[512],locked;
90 static struct termios restios,tios;
91 static char restios_yes;
95 #ifndef PRINTF_WORKS_PM
98 const char *fmt,va_list ap)
108 if (gethostname(host,sizeof(host))) strcpy(host,"<ERROR>");
112 if ((s=strchr(ctm,'\n'))) *s='\0';
113 fprintf(logf,"%s %s %s[%d]: ",ctm,host,pname,mypid);
114 vfprintf(logf,fmt,ap);
115 #ifndef PRINTF_WORKS_PM
116 if (outerr) fputs(strerror(errno),logf);
122 static void logmsg(const char *fmt,...)
127 #ifndef PRINTF_WORKS_PM
134 static void error(const char *fmt,...)
138 #ifndef PRINTF_WORKS_PM
143 if (fatal=='!' || fatal=='.' || fatal=='\n') fmt++;
146 #ifndef PRINTF_WORKS_PM
147 if (!(nfmt=strdup(fmt))) return;
149 if ((pm=(fmtl>=2 && !strcmp(fmt+fmtl-2,"%m")))) nfmt[fmtl-2]='\0';
152 fprintf(stderr,"%s: ",pname);
155 #ifdef PRINTF_WORKS_PM
161 if (fatal=='!') vlogmsg(
162 #ifdef PRINTF_WORKS_PM
170 #ifndef PRINTF_WORKS_PM
172 fputs(strerror(errno),stderr);
177 if (fatal!='\n') fputc((fatal=='.'?'.':'!'),stderr);
179 if (fatal=='!') exit(EXIT_FAILURE);
182 static void chk(void *p)
185 error("!Virtual memory exhausted");
188 static void cleanup(void)
191 if (dis_cleanup) return;
193 if (tcsetattr(devfd,TCSANOW,&restios))
194 error("Error restoring termios for device: %m");
197 if (locked && *lockreal) {
198 d2("Removing lockfile \"%s\"\n",lockreal);
199 if (unlink(lockreal))
200 error("Error removing my device lockfile \"%s\": %m",lockreal);
207 static void usage(void)
213 Usage: " PACKAGE " [-c|--config <cfgfile>] [-d|--device <device>]\n\
215 [-l|--lockfile <lock>] [-s|--smsc <smsc #>] [-m|--maxretry <#>]\n\
216 [-r|--readtime <sec>] [-t|--chartime <msec>] [-T|--cmdtime <msec>]\n\
217 [-f|--file] [-v|--verbose] [-h|--help] [-V|--version]\n\
218 <dest. phone> <msg text|msg filename>\n\
220 -c, --config\tRead this additional config file\n\
221 \t\t(def. \"" CONFIG_MAIN "\" and \"$HOME" CONFIG_HOME "\")\n\
222 -d, --device\tMobilDock on this serial device (def. \"" DEF_DEVICE "\")\n\
223 -L, --log\tLog all important messages to this file (def. \"" DEF_LOGNAME "\")\n\
224 -l, --lockfile\tLock serial port by this file, \"%%s\" is basename of device\n\
226 -s, --smsc\tUse this SMS Center number (def. query from Siemens A1)\n\
227 -m, --maxretry\tMaximum retries of any command before giving up (def. %d)\n\
228 -r, --readtime\tSeconds for maximum wait time for response (def. %ds)\n\
229 -t, --chartime\tMilliseconds between each char on baud 19200 (def. %dms)\n\
230 -T, --cmdtime\tMilliseconds before each whole AT command (def. %dms)\n\
231 -f, --file\tRead contents of message from file instead\n\
232 -v, --verbose\tIncrease verbosity level, more \"-v\"s give more messages\n\
233 -h, --help\tPrint a summary of the options\n\
234 -V, --version\tPrint the version number\n\
235 \n",version,DEF_LOCKFILE,DEF_MAXRETRY,DEF_READTIME,DEF_CHARTIME,DEF_CMDTIME);
239 static const struct option longopts[]={
243 {"lockfile",1,0,'l'},
245 {"maxretry",1,0,'m'},
246 {"readtime",1,0,'r'},
247 {"chartime",1,0,'t'},
248 {"cmdtime" ,1,0,'T'},
250 {"verbose" ,0,0,'v'},
252 {"version" ,0,0,'V'}};
254 static void processargs(int argp,char **args,const char *from);
256 static char *cfgstack[MAXCFGLOOP];
257 static unsigned cfgstacki=0;
259 static void chkfclose(FILE *f,const char *fname)
262 error("Error closing \"%s\": %m",fname);
265 static void readfile(const char *fname,char quiet)
269 char *args[MAXCFGARGS],*d,*s,blank,quote;
273 static unsigned tot=0;
275 if (tot++>=MAXCFGNUM) {
276 if (tot==MAXCFGNUM+1) error("Too many config files to read, max is %d, break-out",MAXCFGNUM);
279 if (!(f=fopen(fname,"rt"))) {
280 if (!quiet) error("Can't open config file \"%s\" for r/o: %m",fname);
283 if (verbose>=2) error(".Reading config file \"%s\"",fname);
284 if (fseek(f,0,SEEK_END))
285 error("Error seeking to end of \"s\": %m",fname);
286 if ((size=ftell(f))<0)
287 size=0,error("Error measuring \"%s\": %m",fname);
289 error("File \"%s\" is too long, read only %ld bytes",fname,MAXCONFIG);
290 chk(buf=malloc((size?size:MAXCONFIG)+1));
292 got=fread(buf,1,(size?size:MAXCONFIG),f);
293 if (size && got!=size)
294 error("File \"%s\" read error, got only %u bytes of %ld",fname,got,size);
298 for (argp=1,d=s=buf,blank=1,quote=0;s<buf+got;s++) {
301 if (!quote && isspace(c)) {
305 if (verbose>=2) error("\nConfig \"%s\": arg#%d: %s",fname,argp-1,args[argp-1]);
310 if (argp>=NELEM(args)-1) {
311 error("Too many arguments in \"%s\", from offset %d ignored",fname,s-buf);
318 if (c=='\\') { *d++=*++s; continue; }
319 if (c=='"' || c=='\'') {
320 if (!quote ) { quote=c; continue; }
321 if ( quote==c) { quote=0; continue; }
327 processargs(argp,args,fname);
346 static void processargs(int argp,char **args,const char *from)
349 static unsigned seq=0;
353 optarg=NULL; optind=0; /* FIXME: Possible portability problem. */
354 while ((optc=getopt_long(argp,args,"c:d:L:l:s:m:r:t:T:fvhV",longopts,NULL))!=EOF) switch (optc) {
356 if (cfgstacki>=NELEM(cfgstack)) {
357 error("Looping (%d) during attempt to read config file \"%s\", break-out",NELEM(cfgstack),optind);
360 chk(cfgstack[cfgstacki++]=strdup(optarg));
362 case 'd': case 'L': case 'l': case 's': case 'm': case 'r': case 't': case 'T':
363 for (i=0;i<NELEM(optset);i++)
364 if (optset[i].c==optc) {
365 if (optset[i].stamp && optset[i].stamp!=seq) {
366 assert(!!*optset[i].var);
369 free(*optset[i].var);
370 chk(*optset[i].var=strdup(optarg));
374 assert(i<NELEM(optset));
383 fprintf(stderr,version);
387 error("\nLast getopt(3) error occured during parsing option %d from \"%s\"! Follows help:",optind-1,from);
391 if (!phone && optind<argp)
392 chk(phone=strdup(args[optind++]));
393 if (!body && optind<argp) {
397 for (i=optind,bodylen=argp-optind;i<argp;i++)
398 bodylen+=strlen(args[i]);
399 chk(body=malloc(bodylen));
400 for (d=body,i=optind;i<argp;i++) {
401 size_t l=strlen(args[i]);
405 assert(d<=body+bodylen);
407 assert(d==body+bodylen);
412 char *s=cfgstack[--cfgstacki];
414 assert(cfgstacki>=0);
417 assert(cfgstacki>=0 && cfgstacki<NELEM(cfgstack));
421 static const struct {
425 {&phone,"destination phone number"},
427 {&body ,"body text"},
428 {&device,"device for communication"},
431 static char **emptycheck[]={&logname,&smsc,&body};
433 static void lockclose(int fd)
436 error("Error closing lockfile \"%s\"",lockreal);
439 static inline void lockdevice(void)
449 if (fd!=-1) lockclose(fd);
451 if (delay) sleep(delay);
452 delay=DEVLOCK_PERIOD;
453 if (verbose>=3) error(".Checking the lockfile \"%s\"..",lockreal);
454 if ((fd=open(lockreal,O_RDONLY))==-1) break;
455 if ((got=read(fd,buf,sizeof(buf)-1))<=0) {
457 if (empty>=DEVLOCK_MAXEMPTY) {
458 error(".Lockfile \"%s\" is still not valid, removing it",lockreal);
464 assert(got<sizeof(buf));
466 if (sscanf(buf,"%d",&pid)!=1) goto isempty;
469 if (kill(pid,0) && errno!=ESRCH && errno!=EPERM)
470 error("Error during checking consciousness of PID %d: %m",pid);
471 if (errno!=ESRCH) continue;
472 error(".Lockfile \"%s\" is stale (PID %d), removing it",lockreal,pid);
475 if (unlink(lockreal))
476 error("Error removing foreign lockfile \"%s\": %m",lockreal);
480 if ((fd=open(lockreal,O_WRONLY|O_CREAT|O_EXCL,0644))==-1) {
481 if (errno==EEXIST) goto recheck;
482 error("!Error creating lockfile \"%s\": %m",lockreal);
485 got=VARPRINTF(buf,"%010d\n",getpid()); assert(got==11);
486 if (write(fd,buf,got)!=got)
487 error("!Error writing data to lockfile \"%s\": %m",lockreal);
491 static char wasalarm=0;
492 static void sigalarm(int signo)
494 signal(SIGALRM,(RETSIGTYPE (*)(int))sigalarm);
496 if (verbose>=1) error("Timed out");
499 static void blocking(char yes)
501 static char state=-1;
502 if (state==yes) return;
503 if (fcntl(devfd,F_SETFL,(yes?0:O_NONBLOCK)))
504 error("!fcntl() on device for %sblocking mode: %m",(yes?"":"non-"));
508 static const char *record;
509 static char *catchdata;
510 static size_t catchdatal,catchdatasiz;
512 static void catched(const char *end)
519 if ((p=memchr(record,'\n',end-record))) end=p;
520 if ((len=end-record)) {
521 if (catchdatal+len>catchdatasiz)
522 chk(catchdata=realloc(catchdata,
523 (catchdatasiz=MAX(LINE_MAX,(catchdatal+len)*2))));
524 memcpy(catchdata+catchdatal,record,len);
528 assert(catchdatal<=catchdatasiz);
531 static int retrycnt=0;
532 static void retrying(void)
534 if (++retrycnt>maxretryn) error("!Maximum command retry count (%d) exceeded",maxretryn);
535 if (verbose>=2) error(".Retrying phase, %d out of %d..",retrycnt,maxretryn);
538 static char *devcmd(const char *term,const char *catch,const char *send,...)
540 size_t l,bufl,terml,catchl,fragl,offs;
547 if (!term) term="\nOK\n";
548 if ((errout=(*send=='!'))) send++;
552 if (errout) return(NULL);
557 l=VARVPRINTF(buf,send,ap); bufl=l+1;
559 if (bufl>=sizeof(buf)-1) error("!Command too big (%d>%d)",bufl,sizeof(buf)-1);
560 if (verbose>=2) error(".devcmd(send=\"%s\",term=\"%s\",catch=\"%s\")",buf,term,catch);
561 buf[l]='\r'; buf[l+1]='\n';
562 for (offs=0,got=0;offs<bufl;offs++) {
564 usleep((offs?chartimen:cmdtimen)*1000);
565 if (!offs && tcflush(devfd,TCIOFLUSH))
566 error("Error flushing I/O queue of device: %m");
567 if (write(devfd,buf+offs,1)!=1) break;
570 error("Error forcing output of char %d of cmd \"%s\": %m",offs,buf);
574 error("Wrote only %d of %d bytes of command: %m",got,bufl);
578 if (!(terml=strlen(term))) {
583 catchl=strlen(catch);
584 fragl=MAX(terml,catchl);
587 fragl=MAX(fragl,MAX(strlen(ERROR_SUBSTR1),strlen(ERROR_SUBSTR2)));
595 got=read(devfd,buf+bufl,sizeof(buf)-1-bufl);
596 if (got==-1 && errno==EAGAIN) {
599 got=read(devfd,buf+bufl,1);
602 if (wasalarm) error("!Maximum response timeout (%ds) exceeded",readtimen);
603 error("Couldn't read device data (ret=%d): %m",got);
608 /* FIXME: '\0' conversion */
609 while (buf+bufl>s && (s=memchr(s,'\r',buf+bufl-s))) *s='\n';
610 catched(buf+bufl); assert(!record || record==buf+bufl);
611 assert(bufl<sizeof(buf));
614 assert(strlen(buf)==bufl);
615 /* d3(">%s|%s<\n",buf,term); */
616 if (strstr(buf,ERROR_SUBSTR1) || strstr(buf,ERROR_SUBSTR2)) {
617 error("Found ERROR response on command \"%s\"",send);
620 if (catch && bufl>=catchl && (hit=strstr(buf,catch))) {
622 catched(buf+bufl); assert(!record || record==buf+bufl);
624 if ( bufl>= terml && (hit=strstr(buf,term))) break;
625 memmove(buf,buf+bufl-(fragl-1),fragl-1);
627 if (record) record=buf+bufl;
632 if (!catch) return(NULL);
633 error("Data requested on command \"%s\" but no found after term \"%s\"",send,term);
640 if (verbose>=2) error(".Returning data \"%s\" for cmd \"%s\"",catchdata,send);
644 static int prepaddr(unsigned char *d,const char *addr)
650 if ((plus=(*addr=='+'))) addr++;
651 *++d=(plus?ADDR_INT:ADDR_NAT);
653 if (*addr<'0' || *addr>'9')
654 error("!Error during conversion of number at: %s",addr);
657 if ((flip=!flip)) *++d=0xF0|n;
658 else *d=(*d&0x0F)|(n<<4U);
663 static char *finalsmsc;
664 #define SMSCBINSIZE (1+1+(MAXNUMLEN+1)/2)
665 static char pdusmsc[SMSCBINSIZE*2+1];
667 static inline char tohex(unsigned char x)
670 if (x<10) return(x +'0');
674 static void textconv(char *d,unsigned char *s,size_t len)
684 static inline void smscset(void)
688 unsigned char bin[2+(MAXNUMLEN+1)/2];
690 if (smsc) devcmd(NULL,NULL,"\r\nAT+CSCA=\"%s\"",smsc);
691 s=devcmd(NULL,"\n+CSCA:","\r\nAT+CSCA?");
692 while (isspace(*s)) s++;
693 if (!*s || !strcmp(s,"EMPTY"))
694 error("!No SMS set in A1 found");
695 if (verbose>=1) error("\nFound default SMSC in A1: %s",s);
696 if (*s!='"') error("!No left-quote found in: %s",s);
697 if (!(t=strrchr(s+1,'"'))) error("!No right-quote found in: %s",s);
699 while (isspace(*t)) t++;
700 if (*t++!=',') error("!No comma found after quotes in: %s",s);
701 while (isspace(*t)) t++;
702 l=strtol(t,&serr,10);
703 if ((l!=ADDR_NAT && l!=ADDR_INT) || (serr && *serr))
704 error("!Type parse error in: %s",s);
705 if (l==ADDR_NAT || s[1]=='+') s++;
708 chk(finalsmsc=strdup(s));
709 if (verbose>=2) error("\nDecoded SMSC address: %s",finalsmsc);
710 bin[0]=1+(prepaddr(bin,finalsmsc)+1)/2;
711 textconv(pdusmsc,bin,bin[0]+1);
714 static char *pdudata;
716 static inline unsigned char charconv(char c,size_t offs)
718 if ((c>='A' && c<='Z') || (c>='a' && c<='z') || (c>='0' && c<='9')) return(c);
722 case '"': return(96);
727 error("Can't convert character '%c' (0x%02X) at offs %d (0-based), substituted '?'",
728 c,(unsigned char)c,offs);
732 static inline void genpdu(void)
734 static unsigned char pdu[64+MAXNUMLEN/2+(MAXBODYLEN*7)/8];
735 unsigned char *d=pdu;
737 char inb=0,outb=0,xb;
744 *d=i; d+=1+1+(i+1)/2;
748 if (bodylen>MAXBODYLEN) {
749 error("Body too large (%d>%d), cut",bodylen,MAXBODYLEN);
753 assert(d<pdu+sizeof(pdu));
754 while (bodylen || inb) {
756 assert(bodylen>0); assert(!!*body);
757 inreg=charconv(*body++,offs++);
766 d4("inb=%d,outb=%d,xb=%d\n",inb,outb,xb);
767 *d|=((inreg>>(unsigned)(7-inb))&((1<<xb)-1))<<(unsigned)(8-outb);
771 assert(d<pdu+sizeof(pdu));
772 pdudata=malloc(2*(d-pdu)+1);
773 textconv(pdudata,pdu,d-pdu);
779 const char *const msg;
781 { &maxretry,&maxretryn,"maxretry" },
782 { &readtime,&readtimen,"readtime" },
783 { &chartime,&chartimen,"chartime" },
784 { &cmdtime ,&cmdtimen ,"cmdtime" },
787 int main(int argc,char **argv)
794 if ((s=strrchr((pname=*argv),'/'))) pname=s+1;
796 signal(SIGTERM,(RETSIGTYPE (*)(int))cleanup);
797 signal(SIGQUIT,(RETSIGTYPE (*)(int))cleanup);
798 signal(SIGINT ,(RETSIGTYPE (*)(int))cleanup);
799 signal(SIGHUP ,(RETSIGTYPE (*)(int))cleanup);
800 processargs(argc,argv,"<command-line>");
801 if ((s=getenv("HOME"))) {
803 char *buf=malloc(l+50);
806 strcpy(buf+l,CONFIG_HOME);
810 readfile(CONFIG_MAIN,1);
812 for (i=0;i<NELEM(nullcheck);i++)
813 if (!*nullcheck[i].var) {
814 error("Missing parameter \"%s\"",nullcheck[i].name);
817 if (fatal) error("!Previous error%s considered unrecoverable",(fatal==1?"":"s"));
818 for (i=0;i<NELEM(emptycheck);i++)
819 if (*emptycheck[i] && !**emptycheck[i]) {
820 free(*emptycheck[i]);
823 if (!logname) logname=DEF_LOGNAME;
824 if (!lockfile) lockfile=DEF_LOCKFILE;
825 if (!device) device=DEF_DEVICE;
826 if (body && readbody) {
834 error("\nPlease enter the SMS text body, end with EOF (ctrl-D):");
835 chk(body=malloc(BODYLOAD));
836 bodylen=fread(body,1,BODYLOAD,fin);
838 error("!Error reading stream \"%s\": %m",(finame?finame:"<stdin>"));
841 chkfclose(fin,finame);
845 for (i=0;i<NELEM(numarg);i++) {
847 if (!*numarg[i].sp) continue;
848 *numarg[i].ip=strtol(*numarg[i].sp,&serr,0);
849 if (*numarg[i].ip<0 || *numarg[i].ip>=LONG_MAX || !serr || *serr)
850 error("!Number parse error for parameter \"%s\" of \"%s\" at: %s",
851 numarg[i].msg,*numarg[i].sp,serr);
854 if (!strchr(device,'/')) {
855 size_t l=strlen(device);
856 chk(s=malloc(5+l+1));
862 devicename=strrchr(device,'/')+1; assert(!!(devicename-1));
863 for (i=0,s=lockfile;*s;s++) {
864 if (*s!='%') continue;
866 if (*s=='%') continue;
868 if (i) error("!Only one \"%%s\" permitted in lockfile format-string");
871 error("!Invalid format-character '%c' in lockfile format-string, only \"%%s\" allowed",*s);
875 if (!(logf=fopen(logname,"a")))
876 error("!Error opening log \"%s\" for append: %m",logname);
877 logmsg("Starting up: " PACKAGE " " VERSION);
881 if (lockfile && *lockfile && VARPRINTF(lockreal,lockfile,devicename)>0) {
883 if (verbose>=1) error(".Locking device \"%s\" by \"%s\"..",device,lockreal);
887 if ((end-=start)>LOCKREPORT)
888 logmsg("Device lock succeeded after %d seconds",end);
890 if (verbose>=1) error(".Opening device \"%s\"..",device);
891 if ((devfd=open(device,O_RDWR|O_NDELAY))<0)
892 error("!Cannot open device \"%s\" for rw-access: %m",device);
894 if (tcgetattr(devfd,&restios))
895 error("Unable to get termios settings: %m");
897 restios.c_cflag=(restios.c_cflag&~(CBAUD|CBAUDEX))|B0|HUPCL;
900 tios.c_iflag=IGNBRK|IGNPAR|IXON|IXOFF;
902 tios.c_cflag=CS8|CREAD|CLOCAL|B19200|HUPCL;
903 tios.c_lflag=IEXTEN|NOFLSH;
904 memset(tios.c_cc,_POSIX_VDISABLE,sizeof(tios.c_cc));
907 cfsetispeed(&tios,B19200);
908 if (cfsetospeed(&tios,B19200)|cfsetispeed(&tios,B19200))
909 error("Error setting termios baudrate on device: %m");
910 if (tcflush(devfd,TCIOFLUSH))
911 error("Error flushing termios (TCIOFLUSH) on device: %m");
912 if (tcsetattr(devfd,TCSANOW,&tios))
913 error("!Unable to set initial termios device settings: %m");
915 signal(SIGALRM,(RETSIGTYPE (*)(int))sigalarm);
917 devcmd("",NULL,"\r\nAT\x1A");
918 devcmd(NULL,NULL,"\r\nAT");
920 devcmd(NULL,NULL,"\r\nAT+CMGF=0");
921 devcmd("\n> ",NULL,"\r\nAT+CMGS=%d",(strlen(pdusmsc)+strlen(pdudata))/2);
922 if (!(s=devcmd(NULL,"\n+CMGS:","!%s%s\x1A",pdusmsc,pdudata))) retrying();
924 while (isspace(*s)) s++;
925 if (verbose>=1) error("\nMessage successfuly sent with MR: %s",s);
926 devcmd(NULL,NULL,"\r\nAT");
928 logmsg("SMS sent (after %d retries), message reference: %s",retrycnt,s);
929 return(EXIT_SUCCESS);