3 static char rcsid[] ATTR_UNUSED = "$Id$";
8 * Revision 1.1.1.1 1999/05/26 13:06:26 short
26 #include <sys/types.h>
32 #ifdef HAVE_GETOPT_LONG
39 char *strdup(const char *s);
40 int kill(pid_t pid,int sig);
41 int snprintf(char *str,size_t n,const char *format,...);
42 int vsnprintf(char *str,size_t n,const char *format,va_list ap);
43 void usleep(unsigned long usec);
46 #define NELEM(x) (sizeof((x))/sizeof(*(x)))
53 /* ANSI C does not allow macro with variable arguments */
55 #define dB(a) dbg(fprintf a)
57 #define d1(n1) dB((dO,n1 ))
58 #define d2(n1,n2) dB((dO,n1,n2 ))
59 #define d3(n1,n2,n3) dB((dO,n1,n2,n3 ))
60 #define d4(n1,n2,n3,n4) dB((dO,n1,n2,n3,n4))
62 static const char version[]="This is MobilDock SMS sender (" PACKAGE " " VERSION ")\n";
70 static int dis_cleanup=0,devfd=-1;
72 static char *phone,*body,*device,*lockfile,*smsc,*chartime,*cmdtime;
74 static long chartimen=DEF_CHARTIME,cmdtimen=DEF_CMDTIME;
75 static size_t bodylen;
77 static char *devicename; /* path stripped */
78 static char lockreal[512],locked;
80 static struct termios restios;
81 static char restios_yes;
83 static void error(const char *fmt,...)
87 #ifndef PRINTF_WORKS_PM
92 if (fatal=='!' || fatal=='.' || fatal=='\n') fmt++;
95 #ifndef PRINTF_WORKS_PM
96 if (!(nfmt=strdup(fmt))) return;
98 if ((pm=(fmtl>=2 && !strcmp(fmt+fmtl-2,"%m")))) nfmt[fmtl-2]='\0';
101 fprintf(stderr,"%s: ",pname);
104 #ifdef PRINTF_WORKS_PM
112 #ifndef PRINTF_WORKS_PM
114 fputs(strerror(errno),stderr);
119 if (fatal!='\n') fputc((fatal=='.'?'.':'!'),stderr);
121 if (fatal=='!') exit(EXIT_FAILURE);
124 static void chk(void *p)
127 error("!Virtual memory exhausted");
130 static void cleanup(void)
133 if (dis_cleanup) return;
135 if (tcsetattr(devfd,TCSANOW,&restios))
136 error("Error restoring termios for device: %m");
139 if (locked && *lockreal) {
140 d2("Removing lockfile \"%s\"\n",lockreal);
141 if (unlink(lockreal))
142 error("Error removing my device lockfile \"%s\": %m",lockreal);
149 static void usage(void)
155 Usage: " PACKAGE " [-c|--config <cfgfile>] [-d|--device <device>]\n\
156 [-l|--lockfile <lock>] [-s|--smsc <smsc #>]\n\
157 [-t|--chartime <msec>] [-T|--cmdtime <msec>]\n\
158 [-f|--file] [-v|--verbose] [-h|--help] [-V|--version]\n\
159 <dest. phone> <msg text|msg filename>\n\
161 -c, --config\tRead this additional config file\n\
162 \t\t(def. \"" CONFIG_MAIN "\" and \"$HOME" CONFIG_HOME "\")\n\
163 -d, --device\tMobilDock on this serial device (def. \"" DEF_DEVICE "\")\n\
164 -l, --lockfile\tLock serial port by this file, \"%%s\" is basename of device\n\
166 -s, --smsc\tUse this SMS Center number (def. query from Siemens A1)\n\
167 -t, --chartime\tMilliseconds between each char on baud 19200 (def. %dms)\n\
168 -T, --cmdtime\tMilliseconds before each whole AT command (def. %dms)\n\
169 -f, --file\tRead contents of message from file instead\n\
170 -v, --verbose\tIncrease verbosity level, more \"-v\"s give more messages\n\
171 -h, --help\tPrint a summary of the options\n\
172 -V, --version\tPrint the version number\n\
173 \n",version,DEF_LOCKFILE,DEF_CHARTIME,DEF_CMDTIME);
177 static const struct option longopts[]={
180 {"lockfile",1,0,'l'},
182 {"chartime",1,0,'t'},
183 {"cmdtime" ,1,0,'T'},
185 {"verbose" ,0,0,'v'},
187 {"version" ,0,0,'V'}};
189 static void processargs(int argp,char **args,const char *from);
191 static char *cfgstack[MAXCFGLOOP];
192 static unsigned cfgstacki=0;
194 static void chkfclose(FILE *f,const char *fname)
197 error("Error closing \"%s\": %m",fname);
200 static void readfile(const char *fname,char quiet)
204 char *args[MAXCFGARGS],*d,*s,blank,quote;
208 static unsigned tot=0;
210 if (tot++>=MAXCFGNUM) {
211 if (tot==MAXCFGNUM+1) error("Too many config files to read, max is %d, break-out",MAXCFGNUM);
214 if (!(f=fopen(fname,"rt"))) {
215 if (!quiet) error("Can't open config file \"%s\" for r/o: %m",fname);
218 if (verbose>=2) error(".Reading config file \"%s\"",fname);
219 if (fseek(f,0,SEEK_END))
220 error("Error seeking to end of \"s\": %m",fname);
221 if ((size=ftell(f))<0)
222 size=0,error("Error measuring \"%s\": %m",fname);
224 error("File \"%s\" is too long, read only %ld bytes",fname,MAXCONFIG);
225 chk(buf=malloc((size?size:MAXCONFIG)+1));
227 got=fread(buf,1,(size?size:MAXCONFIG),f);
228 if (size && got!=size)
229 error("File \"%s\" read error, got only %u bytes of %ld",fname,got,size);
233 for (argp=1,d=s=buf,blank=1,quote=0;s<buf+got;s++) {
236 if (!quote && isspace(c)) {
240 if (verbose>=2) error("\nConfig \"%s\": arg#%d: %s",fname,argp-1,args[argp-1]);
245 if (argp>=NELEM(args)-1) {
246 error("Too many arguments in \"%s\", from offset %d ignored",fname,s-buf);
253 if (c=='\\') { *d++=*++s; continue; }
254 if (c=='"' || c=='\'') {
255 if (!quote ) { quote=c; continue; }
256 if ( quote==c) { quote=0; continue; }
262 processargs(argp,args,fname);
278 static void processargs(int argp,char **args,const char *from)
281 static unsigned seq=0;
285 optarg=NULL; optind=0; /* FIXME: Possible portability problem. */
286 while ((optc=getopt_long(argp,args,"c:d:l:s:t:T:fvhV",longopts,NULL))!=EOF) switch (optc) {
288 if (cfgstacki>=NELEM(cfgstack)) {
289 error("Looping (%d) during attempt to read config file \"%s\", break-out",NELEM(cfgstack),optind);
292 chk(cfgstack[cfgstacki++]=strdup(optarg));
294 case 'd': case 'l': case 's': case 't': case 'T':
295 for (i=0;i<NELEM(optset);i++)
296 if (optset[i].c==optc) {
297 if (optset[i].stamp && optset[i].stamp!=seq) {
298 assert(!!*optset[i].var);
301 free(*optset[i].var);
302 chk(*optset[i].var=strdup(optarg));
306 assert(i<NELEM(optset));
315 fprintf(stderr,version);
319 error("\nLast getopt(3) error occured during parsing option %d from \"%s\"! Follows help:",optind-1,from);
323 if (!phone && optind<argp)
324 chk(phone=strdup(args[optind++]));
325 if (!body && optind<argp) {
329 for (i=optind,bodylen=argp-optind;i<argp;i++)
330 bodylen+=strlen(args[i]);
331 chk(body=malloc(bodylen));
332 for (d=body,i=optind;i<argp;i++) {
333 size_t l=strlen(args[i]);
337 assert(d<=body+bodylen);
339 assert(d==body+bodylen);
344 char *s=cfgstack[--cfgstacki];
346 assert(cfgstacki>=0);
349 assert(cfgstacki>=0 && cfgstacki<NELEM(cfgstack));
353 static const struct {
357 {&phone,"destination phone number"},
359 {&body ,"body text"},
360 {&device,"device for communication"},
363 static char **emptycheck[]={&smsc,&body};
365 static void lockclose(int fd)
368 error("Error closing lockfile \"%s\"",lockreal);
371 static inline void lockdevice(void)
381 if (fd!=-1) lockclose(fd);
383 if (delay) sleep(delay);
384 delay=DEVLOCK_PERIOD;
385 if (verbose>=3) error(".Checking the lockfile \"%s\"..",lockreal);
386 if ((fd=open(lockreal,O_RDONLY))==-1) break;
387 if ((got=read(fd,buf,sizeof(buf)-1))<=0) {
389 if (empty>=DEVLOCK_MAXEMPTY) {
390 error(".Lockfile \"%s\" is still not valid, removing it",lockreal);
396 assert(got<sizeof(buf));
398 if (sscanf(buf,"%d",&pid)!=1) goto isempty;
401 if (kill(pid,0) && errno!=ESRCH && errno!=EPERM)
402 error("Error during checking consciousness of PID %d: %m",pid);
403 if (errno!=ESRCH) continue;
404 error(".Lockfile \"%s\" is stale (PID %d), removing it",lockreal,pid);
407 if (unlink(lockreal))
408 error("Error removing foreign lockfile \"%s\": %m",lockreal);
412 if ((fd=open(lockreal,O_WRONLY|O_CREAT|O_EXCL,0644))==-1) {
413 if (errno==EEXIST) goto recheck;
414 error("!Error creating lockfile \"%s\": %m",lockreal);
417 got=VARPRINTF(buf,"%010d\n",getpid()); assert(got==11);
418 if (write(fd,buf,got)!=got)
419 error("!Error writing data to lockfile \"%s\": %m",lockreal);
423 static void sigalarm(int signo)
425 if (verbose>=1) error("Timed out");
428 static void blocking(char yes)
430 static char state=-1;
431 if (state==yes) return;
432 if (fcntl(devfd,F_SETFL,(yes?0:O_NONBLOCK)))
433 error("!fcntl() on device for %sblocking mode: %m",(yes?"":"non-"));
437 static const char *record;
438 static char *catchdata;
439 static size_t catchdatal,catchdatasiz;
441 static void catched(const char *end)
448 if ((p=memchr(record,'\n',end-record))) end=p;
449 if ((len=end-record)) {
450 if (catchdatal+len>catchdatasiz)
451 chk(catchdata=realloc(catchdata,
452 (catchdatasiz=MAX(LINE_MAX,(catchdatal+len)*2))));
453 memcpy(catchdata+catchdatal,record,len);
457 assert(catchdatal<=catchdatasiz);
460 static char *devcmd(const char *term,const char *catch,const char *send,...)
462 size_t l,bufl,terml,catchl,fragl,offs;
465 RETSIGTYPE (*origsig)(int);
470 if (!term) term="\nOK\n";
471 if ((errout=(*send=='!'))) send++;
474 if (errout) return(NULL);
475 if (verbose>=2) error(".Retrying last device command..");
479 l=VARVPRINTF(buf,send,ap); bufl=l+1;
481 if (bufl>=sizeof(buf)-1) error("!Command too big (%d>%d)",bufl,sizeof(buf)-1);
482 if (verbose>=2) error(".devcmd(send=\"%s\",term=\"%s\",catch=\"%s\")",buf,term,catch);
483 buf[l]='\r'; buf[l+1]='\n';
484 origsig=signal(SIGALRM,(RETSIGTYPE (*)(int))sigalarm);
485 for (offs=0,got=0;offs<bufl;offs++) {
487 usleep((offs?chartimen:cmdtimen)*1000);
488 if (!offs && tcflush(devfd,TCIOFLUSH))
489 error("Error flushing I/O queue of device: %m");
490 if (write(devfd,buf+offs,1)!=1) break;
493 error("Error forcing output of char %d of cmd \"%s\": %m",offs,buf);
496 signal(SIGALRM,origsig);
498 error("Wrote only %d of %d bytes of command: %m",got,bufl);
502 if (!(terml=strlen(term))) {
507 catchl=strlen(catch);
508 fragl=MAX(terml,catchl);
511 fragl=MAX(fragl,MAX(strlen(ERROR_SUBSTR1),strlen(ERROR_SUBSTR2)));
517 got=read(devfd,buf+bufl,sizeof(buf)-1-bufl);
518 if (got==-1 && errno==EAGAIN) {
521 got=read(devfd,buf+bufl,1);
524 error("Could read device data (ret=%d): %m",got);
529 /* FIXME: '\0' conversion */
530 while (buf+bufl>s && (s=memchr(s,'\r',buf+bufl-s))) *s='\n';
531 catched(buf+bufl); assert(!record || record==buf+bufl);
532 assert(bufl<sizeof(buf));
535 assert(strlen(buf)==bufl);
536 /* d3(">%s|%s<\n",buf,term); */
537 if (strstr(buf,ERROR_SUBSTR1) || strstr(buf,ERROR_SUBSTR2)) {
538 error("Found ERROR response on command \"%s\"",send);
541 if (catch && bufl>=catchl && (hit=strstr(buf,catch))) {
543 catched(buf+bufl); assert(!record || record==buf+bufl);
545 if ( bufl>= terml && (hit=strstr(buf,term))) break;
546 memmove(buf,buf+bufl-(fragl-1),fragl-1);
548 if (record) record=buf+bufl;
552 if (!catch) return(NULL);
553 error("Data requested on command \"%s\" but no found after term \"%s\"",send,term);
560 if (verbose>=2) error(".Returning data \"%s\" for cmd \"%s\"",catchdata,send);
564 static int prepaddr(unsigned char *d,const char *addr)
570 if ((plus=(*addr=='+'))) addr++;
571 *++d=(plus?ADDR_INT:ADDR_NAT);
573 if (*addr<'0' || *addr>'9')
574 error("!Error during conversion of number at: %s",addr);
577 if ((flip=!flip)) *++d=0xF0|n;
578 else *d=(*d&0x0F)|(n<<4U);
583 static char *finalsmsc;
584 #define SMSCBINSIZE (1+1+(MAXNUMLEN+1)/2)
585 static char pdusmsc[SMSCBINSIZE*2+1];
587 static inline char tohex(unsigned char x)
590 if (x<10) return(x +'0');
594 static void textconv(char *d,unsigned char *s,size_t len)
604 static inline void smscset(void)
608 unsigned char bin[2+(MAXNUMLEN+1)/2];
610 if (smsc) devcmd(NULL,NULL,"\r\nAT+CSCA=\"%s\"",smsc);
611 s=devcmd(NULL,"\n+CSCA:","\r\nAT+CSCA?");
612 while (isspace(*s)) s++;
613 if (!*s || !strcmp(s,"EMPTY"))
614 error("!No SMS set in A1 found");
615 if (verbose>=1) error("\nFound default SMSC in A1: %s",s);
616 if (*s!='"') error("!No left-quote found in: %s",s);
617 if (!(t=strrchr(s+1,'"'))) error("!No right-quote found in: %s",s);
619 while (isspace(*t)) t++;
620 if (*t++!=',') error("!No comma found after quotes in: %s",s);
621 while (isspace(*t)) t++;
622 l=strtol(t,&serr,10);
623 if ((l!=ADDR_NAT && l!=ADDR_INT) || (serr && *serr))
624 error("!Type parse error in: %s",s);
625 if (l==ADDR_NAT || s[1]=='+') s++;
628 chk(finalsmsc=strdup(s));
629 if (verbose>=2) error("\nDecoded SMSC address: %s",finalsmsc);
630 bin[0]=1+(prepaddr(bin,finalsmsc)+1)/2;
631 textconv(pdusmsc,bin,bin[0]+1);
634 static char *pdudata;
636 static inline unsigned char charconv(char c,size_t offs)
638 if ((c>='A' && c<='Z') || (c>='a' && c<='z') || (c>='0' && c<='9')) return(c);
642 case '"': return(96);
647 error("Can't convert character '%c' (0x%02X) at offs %d (0-based), substituted '?'",
648 c,(unsigned char)c,offs);
652 static inline void genpdu(void)
654 static unsigned char pdu[64+MAXNUMLEN/2+(MAXBODYLEN*7)/8];
655 unsigned char *d=pdu;
657 char inb=0,outb=0,xb;
664 *d=i; d+=1+1+(i+1)/2;
668 if (bodylen>MAXBODYLEN) {
669 error("Body too large (%d>%d), cut",bodylen,MAXBODYLEN);
673 assert(d<pdu+sizeof(pdu));
674 while (bodylen || inb) {
676 assert(bodylen>0); assert(!!*body);
677 inreg=charconv(*body++,offs++);
686 d4("inb=%d,outb=%d,xb=%d\n",inb,outb,xb);
687 *d|=((inreg>>(unsigned)(7-inb))&((1<<xb)-1))<<(unsigned)(8-outb);
691 assert(d<pdu+sizeof(pdu));
692 pdudata=malloc(2*(d-pdu)+1);
693 textconv(pdudata,pdu,d-pdu);
699 const char *const msg;
701 { &chartime,&chartimen,"chartime" },
702 { &cmdtime ,&cmdtimen ,"cmdtime" },
705 int main(int argc,char **argv)
715 signal(SIGTERM,(RETSIGTYPE (*)(int))cleanup);
716 signal(SIGQUIT,(RETSIGTYPE (*)(int))cleanup);
717 signal(SIGINT ,(RETSIGTYPE (*)(int))cleanup);
718 signal(SIGHUP ,(RETSIGTYPE (*)(int))cleanup);
719 processargs(argc,argv,"<command-line>");
720 if ((s=getenv("HOME"))) {
722 char *buf=malloc(l+50);
725 strcpy(buf+l,CONFIG_HOME);
729 readfile(CONFIG_MAIN,1);
731 for (i=0;i<NELEM(nullcheck);i++)
732 if (!*nullcheck[i].var) {
733 error("Missing parameter \"%s\"",nullcheck[i].name);
736 if (fatal) error("!Previous error%s considered unrecoverable",(fatal==1?"":"s"));
737 for (i=0;i<NELEM(emptycheck);i++)
738 if (*emptycheck[i] && !**emptycheck[i]) {
739 free(*emptycheck[i]);
742 if (!lockfile) lockfile=DEF_LOCKFILE;
743 if (!device) device=DEF_DEVICE;
744 if (body && readbody) {
752 error("\nPlease enter the SMS text body, end with EOF (ctrl-D):");
753 chk(body=malloc(BODYLOAD));
754 bodylen=fread(body,1,BODYLOAD,fin);
756 error("!Error reading stream \"%s\": %m",(finame?finame:"<stdin>"));
759 chkfclose(fin,finame);
763 for (i=0;i<NELEM(numarg);i++) {
765 if (!*numarg[i].sp) continue;
766 *numarg[i].ip=strtol(*numarg[i].sp,&serr,0);
767 if (*numarg[i].ip<0 || *numarg[i].ip>=LONG_MAX || !serr || *serr)
768 error("!Number parse error for parameter \"%s\" of \"%s\" at: %s",
769 numarg[i].msg,*numarg[i].sp,serr);
772 if (!strchr(device,'/')) {
773 size_t l=strlen(device);
774 chk(s=malloc(5+l+1));
780 devicename=strrchr(device,'/')+1; assert(!!(devicename-1));
781 for (i=0,s=lockfile;*s;s++) {
782 if (*s!='%') continue;
784 if (*s=='%') continue;
786 if (i) error("!Only one \"%%s\" permitted in lockfile format-string");
789 error("!Invalid format-character '%c' in lockfile format-string, only \"%%s\" allowed",*s);
793 if (lockfile && *lockfile && VARPRINTF(lockreal,lockfile,devicename)>0) {
794 if (verbose>=1) error(".Locking device \"%s\" by \"%s\"..",device,lockreal);
797 if (verbose>=1) error(".Opening device \"%s\"..",device);
798 if ((devfd=open(device,O_RDWR|O_NDELAY))<0)
799 error("!Cannot open device \"%s\" for rw-access: %m",device);
801 if (tcgetattr(devfd,&restios))
802 error("Unable to get termios settings: %m");
804 restios.c_cflag=(restios.c_cflag&~(CBAUD|CBAUDEX))|B0|HUPCL;
807 tios.c_iflag=IGNBRK|IGNPAR|IXON|IXOFF;
809 tios.c_cflag=CS8|CREAD|CLOCAL|B19200|HUPCL;
810 tios.c_lflag=IEXTEN|NOFLSH;
811 memset(tios.c_cc,_POSIX_VDISABLE,sizeof(tios.c_cc));
814 if (tcflush(devfd,TCIOFLUSH))
815 error("Error flushing termios (TCIOFLUSH) on device: %m");
816 if (tcsetattr(devfd,TCSANOW,&tios))
817 error("!Unable to set initial termios device settings");
820 devcmd("",NULL,"\r\nAT\x1A");
821 devcmd(NULL,NULL,"\r\nAT");
823 devcmd(NULL,NULL,"\r\nAT+CMGF=0");
824 devcmd("\n> ",NULL,"\r\nAT+CMGS=%d",(strlen(pdusmsc)+strlen(pdudata))/2);
825 s=devcmd(NULL,"\n+CMGS:","!%s%s\x1A",pdusmsc,pdudata);
827 while (isspace(*s)) s++;
828 if (verbose>=1) error("\nMessage successfuly sent with MR: %s",s);
829 devcmd(NULL,NULL,"\r\nAT");
831 return(EXIT_SUCCESS);