3 static char rcsid[] ATTR_UNUSED = "$Id$";
38 #ifdef HAVE_SYS_TYPES_H
39 #include <sys/types.h>
41 #ifdef HAVE_SYS_STAT_H
53 #ifdef HAVE_SYS_TIME_H
56 #ifdef HAVE_SYS_POLL_H
63 #ifdef HAVE_GETOPT_LONG
69 #define NELEM(x) (sizeof((x))/sizeof(*(x)))
76 /* ANSI C does not allow macro with variable arguments */
78 #define dB(a) dbg(fprintf a)
80 #define d1(n1) dB((dO,n1 ))
81 #define d2(n1,n2) dB((dO,n1,n2 ))
82 #define d3(n1,n2,n3) dB((dO,n1,n2,n3 ))
83 #define d4(n1,n2,n3,n4) dB((dO,n1,n2,n3,n4 ))
84 #define d5(n1,n2,n3,n4,n5) dB((dO,n1,n2,n3,n4,n5 ))
85 #define d6(n1,n2,n3,n4,n5,n6) dB((dO,n1,n2,n3,n4,n5,n6 ))
86 #define d7(n1,n2,n3,n4,n5,n6,n7) dB((dO,n1,n2,n3,n4,n5,n6,n7 ))
87 #define d8(n1,n2,n3,n4,n5,n6,n7,n8) dB((dO,n1,n2,n3,n4,n5,n6,n7,n8))
89 static const char version[]="Mobile Device SMS tool (" PACKAGE " " VERSION ")\n";
97 static int dis_cleanup=0,devfd=-1;
99 static char *phone,*device,*logname,*lockfile,*smsc,*maxretry,*readtime,*chartime,*cmdtime,*baud,*restore;
101 static long maxretryn=DEF_MAXRETRY,readtimen=-1,chartimen=DEF_CHARTIME,cmdtimen=DEF_CMDTIME,baudn=DEF_BAUD;
102 static size_t bodylen;
103 /* --send / --send-mobildock / --receive specific */
105 /* --logo-send specific */
106 static char *logoname,*gsmnet;
107 /* --ring-send specific */
108 static char *ringname;
110 static enum modenum {
112 /* must differ from regular char-s */
114 MODE_SEND =MODE_FIRST+0, /* --send / --send-mobildock */
115 MODE_SEND_MOBILDOCK=MODE_FIRST+1, /* --send-mobildock in before readtimen is set */
116 MODE_RECEIVE =MODE_FIRST+2, /* --receive */
117 MODE_LOGO_SEND =MODE_FIRST+3, /* --logo-send */
118 MODE_RING_SEND =MODE_FIRST+4 /* --ring-send */
120 #define MODE_ORDER(x) ((x)-MODE_FIRST)
121 #define MODE_NAME(x) (longopts[MODE_ORDER((x))].name)
122 #define MODE_BIT(x) (1<<MODE_ORDER((x)))
124 static unsigned mode_stamp;
126 /* pdusmsc variable has to be filled in */
127 #define NEED_PDUSMSC() (mode==MODE_SEND)
129 static char *devicename; /* path stripped */
130 static char lockreal[512],locked;
132 static struct termios restios,tios;
133 static char restios_yes;
136 static void vlogmsg(char pm,char fatal,const char *fmt,va_list ap) ATTR_PRINTFORMAT(3,0);
137 static void vlogmsg(char pm,char fatal,const char *fmt,va_list ap)
147 if (gethostname(host,sizeof(host))) strcpy(host,_("<ERROR>"));
151 if ((s=strchr(ctm,'\n'))) *s='\0';
152 fprintf(logf,"%s %s %s[%d]: ",ctm,host,pname,mypid);
153 vfprintf(logf,fmt,ap);
154 if (pm) { fputs(": ",logf); fputs(strerror(errno),logf); }
155 if (fatal!='\n') fputc((fatal=='.'?'.':'!'),logf);
160 static void logmsg(const char *fmt,...) ATTR_PRINTFORMAT(1,2);
161 static void logmsg(const char *fmt,...)
165 vlogmsg(0,'\n',fmt,ap);
169 static void error(const char *fmt,...) ATTR_PRINTFORMAT(1,2);
170 static void error(const char *fmt,...)
175 if ((pm=(*fmt=='^'))) fmt++;
177 if (fatal=='!' || fatal=='.' || fatal=='\n') fmt++;
180 fprintf(stderr,"%s: ",pname);
182 vfprintf(stderr,fmt,ap);
183 if (fatal=='!') vlogmsg(pm,fatal,fmt,ap);
185 if (pm) { fputs(": ",stderr); fputs(strerror(errno),stderr); }
186 if (fatal!='\n') fputc((fatal=='.'?'.':'!'),stderr);
188 if (fatal=='!') exit(EXIT_FAILURE);
191 static void chk(const void *p)
194 error(_("!Virtual memory exhausted"));
197 static char *devcmd(const char *term,const char *catch,const char *send,...) ATTR_PRINTFORMAT(3,4);
199 static void unlockdevice(int hard)
201 d2("unlockdevice(), locked=%d\n",locked);
202 if (!locked || !*lockreal) return;
203 if (!hard && locked>1) { locked--; return; }
204 d2("Removing lockfile \"%s\"\n",lockreal);
205 if (unlink(lockreal))
206 error(_("^Error removing my device lockfile \"%s\""),lockreal);
210 static void cleanup(void)
213 if (dis_cleanup) return;
217 devcmd(NULL,NULL,"\r\nAT");
218 devcmd(NULL,NULL,cmd);
219 devcmd(NULL,NULL,"\r\nAT");
222 if (tcsetattr(devfd,TCSANOW,&restios))
223 error(_("^Error restoring termios for device"));
231 static void usage(void)
237 Usage: %s [-c|--config <cfgfile>] [-d|--device <device>]\n\
238 {--send | --send-mobildock | --receive | --logo-send}\n\
239 [-L|--log <file>] [-b|--baud <rate>]\n\
240 [-l|--lockfile <lock>] [-s|--smsc <smsc #>] [-m|--maxretry <#>]\n\
241 [-r|--readtime <sec>] [-t|--chartime <msec>] [-T|--cmdtime <msec>]\n\
242 [-v|--verbose] [-h|--help] [-V|--version]\n\
243 --send / --send-mobildock:\n\
244 [-f|--file] <dest. phone> <msg text|msg filename>\n\
248 <dest. phone> <logo filename> [<GSMnet id>]\n\
250 <dest. phone> <ring filename>\n\
252 -c, --config\tRead this additional config file\n\
253 \t\t(def. \"%s\" and \"$HOME%s\")\n\
254 -d, --device\tMobile on this serial device (def. \"%s\")\n\
255 -L, --log\tLog all important messages to this file (def. \"%s\")\n\
256 -b, --baud\tSet baudrate, 2400-57600 supported (def. %d)\n\
257 -l, --lockfile\tLock serial port by this file, \"%%s\" is basename of device\n\
259 -s, --smsc\tUse this SMS Center number (def. query from mobile)\n\
260 -m, --maxretry\tMaximum retries of any command before giving up (def. %d)\n\
261 -r, --readtime\tSeconds for maximum wait time for response\n\
262 \t\t(def. %ds standard, %ds for MobilDock modes,\n\
263 \t\t multiplied %dx for long cmds)\n\
264 -t, --chartime\tMilliseconds between each char (def. %dms)\n\
265 -T, --cmdtime\tMilliseconds before each whole AT command (def. %dms)\n\
266 -v, --verbose\tIncrease verbosity level, more \"-v\"s give more messages\n\
267 -h, --help\tPrint a summary of the options\n\
268 -V, --version\tPrint the version number\n\
270 --send / --send-mobildock:\n\
271 -f, --file\tRead contents of message from file instead\n\
273 <command name>\tProgram to run on receive, message will be on stdin\n\
274 \t\tFollowing substitutes are recognized:\n\
275 \t\t%%p - source phone number\n\
276 \t\t%%T - timestamp from SMSC as # of seconds from 1970 (-1 if invalid)\n\
277 \t\t%%t - ctime(3) style timestamp (e.g. \"Wed Jun 30 21:49:08 1993\"),\n\
278 \t\t empty string if invalid\n\
279 \t\t%%s - originating SMSC number, if available (else empty)\n\
281 <GSMnet id>\t* Oper. logo: Enter custom network code MccMnc, e.g. 23002\n\
282 \t\t* Oper. logo: Specify \"%s\" to read network code from NOL file\n\
283 \t\t* Group gfx : Specify \"%s\" to send logo as group graphics\n\
285 You may need to use the following line to catch all of this help text:\n\
287 \n"),version,PACKAGE,CONFIG_MAIN,CONFIG_HOME,DEF_DEVICE,DEF_LOGNAME,DEF_BAUD,DEF_LOCKFILE,DEF_MAXRETRY,
288 DEF_READTIME,DEF_READTIME_MOBILDOCK,EXT_READTIME,DEF_CHARTIME,DEF_CMDTIME,
289 WORD_NET,WORD_GROUP);
293 static const struct option longopts[]={
294 /* Modes has to be in-order on exact positions */
295 {"send" ,0,0,MODE_SEND},
296 {"send-mobildock",0,0,MODE_SEND_MOBILDOCK},
297 {"receive" ,0,0,MODE_RECEIVE},
298 {"logo-send" ,0,0,MODE_LOGO_SEND},
299 {"ring-send" ,0,0,MODE_RING_SEND},
300 /* Mode aliases may follow in no particular order *
301 * as long as no non-mode options is between them */
302 {"send-md" ,0,0,MODE_SEND_MOBILDOCK},
303 {"recv" ,0,0,MODE_RECEIVE},
304 {"logo" ,0,0,MODE_LOGO_SEND},
305 {"ring" ,0,0,MODE_RING_SEND},
310 {"lockfile",1,0,'l'},
312 {"maxretry",1,0,'m'},
313 {"readtime",1,0,'r'},
314 {"chartime",1,0,'t'},
315 {"cmdtime" ,1,0,'T'},
317 {"verbose" ,0,0,'v'},
319 {"version" ,0,0,'V'},
322 static void processargs(int argp,char **args,const char *from);
324 static char *cfgstack[MAXCFGLOOP];
325 static unsigned cfgstacki=0;
327 static void chkfclose(FILE *f,const char *fname)
330 error(_("^Error closing \"%s\""),fname);
333 static long getfilesize(FILE *f,const char *fname)
337 if (fseek(f,0,SEEK_END))
338 error(_("^Error seeking to end of \"%s\""),fname);
339 if ((size=ftell(f))<0)
340 size=-1,error(_("^Error measuring length of \"%s\""),fname);
345 static void readfile(const char *fname,char quiet)
349 char *args[MAXCFGARGS],*d,*s,blank,quote;
353 static unsigned tot=0;
355 if (tot++>=MAXCFGNUM) {
356 if (tot==MAXCFGNUM+1) error(_("Too many config files to read, max is %d, break-out"),MAXCFGNUM);
359 if (!(f=fopen(fname,"rt"))) {
360 if (!quiet) error(_("^Can't open config file \"%s\" for r/o"),fname);
364 if (verbose>=2) error(_(".Reading config file \"%s\""),fname);
365 if ((size=getfilesize(f,fname))==-1) size=0;
367 error(_("File \"%s\" is too long, read only %d bytes"),fname,MAXCONFIG);
368 chk(buf=malloc((size?size:MAXCONFIG)+1));
369 got=fread(buf,1,(size?size:MAXCONFIG),f);
370 if (size && got!=size)
371 error(_("File \"%s\" read error, got only %u bytes of %ld"),fname,got,size);
375 for (argp=1,d=s=buf,blank=1,quote=0;s<buf+got;s++) {
378 if (!quote && isspace(c)) {
382 if (verbose>=2) error(_("\nConfig \"%s\": arg#%d: %s"),fname,argp-1,args[argp-1]);
387 if (argp>=NELEM(args)-1) {
388 error(_("Too many arguments in \"%s\", from offset %d ignored"),fname,s-buf);
395 if (c=='\\') { *d++=*++s; continue; }
396 if (c=='"' || c=='\'') {
397 if (!quote ) { quote=c; continue; }
398 if ( quote==c) { quote=0; continue; }
404 processargs(argp,args,fname);
408 static struct argstack {
409 struct argstack *next;
415 static struct argstack **argstack_tail=&argstack;
416 static size_t lastargstack_len;
417 static const char *lastargstack_from;
418 static int lastargstack_index;
420 static size_t argstack_size;
421 static int argstack_num;
423 static void pushargstack(char **args,int num,int offset,const char *from,char stack)
430 chk(as=malloc(sizeof(*as)+sizeof(as->arg)*(num-1)));
433 if (!from) as->from=NULL;
434 else chk(as->from=strdup(from));
435 for (i=0;i<num;i++) {
436 chk(as->arg[i]=strdup(args[i]));
437 argstack_size+=strlen(args[i]);
447 argstack_tail=&as->next;
451 static void pushargstack_one(char *s,char stack)
452 { pushargstack(&s,1,0,NULL,stack); }
454 static char *nextargstack(void)
459 if (argstack && order==argstack->num) {
460 struct argstack *as=argstack;
461 if (!(argstack=as->next))
462 argstack_tail=&argstack;
464 free((char *)as->from);
465 lastargstack_from=NULL;
469 assert(!argstack_num); assert(!argstack_size);
472 assert(order<argstack->num);
473 lastargstack_index=argstack->offset+order;
474 r=argstack->arg[order++];
475 assert(argstack_num>0); argstack_num--;
476 lastargstack_len=strlen(r);
477 assert(argstack_size>=lastargstack_len); argstack_size-=lastargstack_len;
478 lastargstack_from=argstack->from;
482 static char *glueargstack(size_t *destlenp,const char *glue)
484 size_t gluel=(glue?strlen(glue):0),destlen;
488 chk(dest=strdup(""));
489 if (destlenp) *destlenp=0;
492 destlen=argstack_size+(argstack_num-1)*gluel;
493 if (destlenp) *destlenp=destlen;
494 chk(dest=malloc(destlen+1));
495 for (d=dest;(s=nextargstack());) {
496 memcpy(d,s,lastargstack_len);
499 if (!argstack_num) break;
501 memcpy(d,glue,gluel);
503 assert(d<=dest+destlen);
505 assert(!argstack_num);
506 assert(d==dest+destlen);
527 static void processargs(int argp,char **args,const char *from)
530 static unsigned seq=0;
534 optarg=NULL; optind=0; /* FIXME: Possible portability problem. */
535 while ((optc=getopt_long(argp,args,"c:d:L:b:l:s:m:r:t:T:fvhV",longopts,NULL))!=EOF) switch (optc) {
537 if (cfgstacki>=NELEM(cfgstack)) {
538 error(_("Looping (%d) during attempt to read config file \"%s\", break-out"),NELEM(cfgstack),from);
541 chk(cfgstack[cfgstacki++]=strdup(optarg));
543 case 'd': case 'L': case 'b': case 'l': case 's': case 'm': case 'r': case 't': case 'T':
544 for (i=0;i<NELEM(optset);i++)
545 if (optset[i].c==optc) {
546 if (optset[i].stamp && optset[i].stamp!=seq) {
547 assert(!!*optset[i].var);
550 free(*optset[i].var);
551 chk(*optset[i].var=strdup(optarg));
555 assert(i<NELEM(optset));
558 case MODE_SEND_MOBILDOCK:
562 if (mode_stamp && mode_stamp!=seq) break;
573 fprintf(stderr,version);
577 error(_("\nLast getopt(3) error occured during parsing option %d from \"%s\"! Follows help:"),optind-1,from);
581 pushargstack(args+optind,argp-optind,optind,from,1);
583 char *s=cfgstack[--cfgstacki];
585 assert(cfgstacki>=0);
588 assert(cfgstacki>=0 && cfgstacki<NELEM(cfgstack));
592 static const struct nullcheck {
597 {&phone,MODE_BIT(MODE_SEND)|MODE_BIT(MODE_SEND_MOBILDOCK)|MODE_BIT(MODE_LOGO_SEND),
598 N_("destination phone number")},
599 {&logoname,MODE_BIT(MODE_LOGO_SEND),N_("logo filename")},
600 {&ringname,MODE_BIT(MODE_RING_SEND),N_("ring filename")},
601 {&body,MODE_BIT(MODE_RECEIVE),N_("body text")}, /* we allow empty bodies for SENDs */
603 {&gsmnet,MODE_BIT(MODE_LOGO_SEND),N_("GSM operator network code")},
604 {&device,0,N_("device for communication")},
607 static char **emptycheck[]={&logname,&smsc,&logoname,&gsmnet};
609 static inline void emptyclean(void)
613 for (i=0;i<NELEM(emptycheck);i++)
614 if (*emptycheck[i] && !**emptycheck[i]) {
615 free(*emptycheck[i]);
620 static inline void cmdline_done(void)
623 while ((s=nextargstack())) {
624 error(_("\nExcessive option %d from \"%s\" ignored: %s"),
625 lastargstack_index,lastargstack_from,s);
631 static char *check_phone(const char *phone)
634 static char err[LINE_MAX];
636 for (s=s1=(phone+(*phone=='+'));*s && s-s1<MAXNUMLEN;s++)
638 VARPRINTF2(err,_("Invalid digit '%c' in phone number - at offset %d"),
642 if (!*s) return(NULL);
643 VARPRINTF2(err,_("Phone number too long (%d), max. %d digits allowed"),
644 strlen(s1),MAXNUMLEN);
648 static void cmdline_phone(void)
650 if (!phone && (phone=nextargstack())) {
653 if ((s=check_phone(phone)))
654 error(_("!%s in option %d from \"%s\": %s"),
655 s,lastargstack_index,lastargstack_from,phone);
659 static inline void cmdline_receive(void)
663 if (!body && argstack_num) {
664 body=glueargstack(&bodylen," ");
665 for (s=body;(s=strchr(s,'%'));s++)
667 case 'p': case 'T': case 't': case 's': break;
669 error(_("Unknown formatsymbol '%c' (use \"%%%%%c\" to fix it) at pos %d in: %s"),
675 static inline void cmdline_send(void)
678 if (!body && argstack_num)
679 body=glueargstack(&bodylen," ");
682 static inline void cmdline_logo_send(void)
687 if (!logoname) logoname=nextargstack();
688 if (!gsmnet && (ogsmnet=nextargstack())) {
691 chk(gsmnet=strdup(ogsmnet));
692 if (strtrycasecmp(gsmnet,WORD_NET) && strtrycasecmp(gsmnet,WORD_GROUP)) {
693 for (d=s=gsmnet;*s;s++) {
694 if (isdigit(*s)) { *d++=*s; continue; }
695 if (isspace(*s)) continue;
696 error(_("\nInvalid characted '%c' in GSMnet at offs %d: %s"),
697 *s,s-gsmnet,ogsmnet);
702 error(_("\nGSMnet is required to have exactly 5 digits or to be\n\
703 either \"%s\" or \"%s\", but found length %d: %s"),
704 WORD_NET,WORD_GROUP,d-gsmnet,ogsmnet);
709 error(_("\nGSMnet option %d from \"%s\" rejected due to previous errors: %s"),
710 lastargstack_index,lastargstack_from,ogsmnet);
718 static inline void cmdline_ring_send(void)
721 if (!ringname) ringname=nextargstack();
724 static void lockclose(int fd)
727 error(_("Error closing lockfile \"%s\""),lockreal);
730 static inline int lockdevice(int attempt)
739 d2("lockdevice(), locked=%d\n",locked);
740 if (locked) return (++locked);
742 if (fd!=-1) lockclose(fd);
744 if (delay) sleep(delay);
745 delay=DEVLOCK_PERIOD;
746 if (verbose>=3) error(_(".Checking the lockfile \"%s\".."),lockreal);
747 if ((fd=open(lockreal,O_RDONLY))==-1) break;
748 if ((got=read(fd,buf,sizeof(buf)-1))<=0) {
750 if (empty>=DEVLOCK_MAXEMPTY) {
751 error(_(".Lockfile \"%s\" is still not valid, removing it"),lockreal);
757 assert(got<sizeof(buf));
759 if (sscanf(buf,"%d",&pid)!=1) goto isempty;
762 if (kill(pid,0) && errno!=ESRCH && errno!=EPERM)
763 error(_("^Error during checking consciousness of PID %d"),pid);
765 if (attempt) return(0);
768 error(_(".Lockfile \"%s\" is stale (PID %d), removing it"),lockreal,pid);
771 if (unlink(lockreal))
772 error(_("^Error removing foreign lockfile \"%s\""),lockreal);
776 if ((fd=open(lockreal,O_WRONLY|O_CREAT|O_EXCL,0644))==-1) {
777 if (errno==EEXIST) goto recheck;
778 error(_("^!Error creating lockfile \"%s\""),lockreal);
781 got=VARPRINTF(buf,"%010d\n",getpid()); assert(got==11);
782 if (write(fd,buf,got)!=got)
783 error(_("^!Error writing data to lockfile \"%s\""),lockreal);
788 static char wasalarm=0;
789 static void sigalarm(int signo);
791 static void setalarm(void)
793 signal(SIGALRM,(RETSIGTYPE (*)(int))sigalarm);
794 #ifdef HAVE_SIGINTERRUPT
795 siginterrupt(SIGALRM,1);
799 static void sigalarm(int signo)
803 if (verbose>=1) error(_("Timed out"));
806 static void blocking(char yes)
808 static char state=-1;
809 if (state==yes) return;
810 if (fcntl(devfd,F_SETFL,(yes?0:O_NONBLOCK)))
811 error(_("^!fcntl() on device for %s mode"),(yes?_("blocking"):_("non-blocking")));
815 static const char *record;
816 static char *catchdata;
817 static size_t catchdatal,catchdatasiz;
819 static void catched(const char *end,char edata)
826 p=memchr(record,edata,end-record);
827 if ((len=(p?p:end)-record)) {
829 chk(catchdata=malloc((catchdatasiz=LINE_MAX)));
830 if (catchdatal+len>catchdatasiz)
831 chk(catchdata=realloc(catchdata,
832 (catchdatasiz=(catchdatal+len)*2)));
833 memcpy(catchdata+catchdatal,record,len);
837 assert(catchdatal<=catchdatasiz);
840 static int retrycnt=0;
841 static void retrying(void)
843 if (maxretryn>=0 && ++retrycnt>maxretryn) error(_("!Maximum command retry count (%ld) exceeded"),maxretryn);
844 if (verbose>=2) error(_(".Retrying phase, %d out of %ld.."),retrycnt,maxretryn);
847 static char *reform(const char *s,int slot)
849 static struct formslot {
856 assert(slot>=0 && slot<NELEM(arr));
857 if (!s) return(_("<unset>"));
858 if (!(fs=&arr[slot])->s)
859 chk(fs->s=malloc(fs->l=LINE_MAX));
861 for (*d++='"';(c=*s);s++) {
862 if (d>=fs->s+fs->l-10) {
864 chk(fs->s=realloc(fs->s,(fs->l=(fs->l?fs->l*2:LINE_MAX))));
867 if (c!='\\' && c!='"' && isprint(c)) { *d++=c; continue; }
870 case '\\': case '"': *d++=c; break;
871 case '\n': *d++='n'; break;
872 case '\r': *d++='r'; break;
873 case '\032': *d++='Z'; break;
874 case '\033': *d++='e'; break;
876 d+=sprintf(d,"x%02X",(unsigned char)c);
884 static char *devcmd(const char *term,const char *catch,const char *send,...) ATTR_PRINTFORMAT(3,4);
885 static char *devcmd(const char *term,const char *catch,const char *send,...)
887 size_t l,bufl2,terml,catchl=0 /* GCC happiness */,fragl,offs;
888 static char buf[LINE_MAX];
893 char errout,extend,noconvcr,edata;
896 static const char emptystring[]="";
898 if (!term) term="\nOK\n";
899 if (!strcmp(send," ")) send=NULL; /* GCC formatstring-check workaround */
900 if (!(osend=send)) send="";
901 if ((noconvcr=(catch && *catch=='@'))) catch++;
902 if ((errout=(*send=='!'))) send++;
903 errout|=(maxretryn==-1);
904 if ((extend=(*send=='~'))) send++;
905 alarmtime=readtimen*(extend?EXT_READTIME:1);
906 d8("devcmd(), alarmtime=%ld, errout=%d, extend=%d, noconvcr=%d, osend=%p, bufl=%d, buf: %s\n",
907 alarmtime,errout,extend,noconvcr,osend,bufl,reform(buf,0));
911 if (errout) return(NULL);
917 d1("Resetting bufl.\n");
919 l=VARVPRINTF(buf,send,ap); bufl=l+(!!osend);
921 if (bufl>=sizeof(buf)-1) error(_("!Command too big (%d>%d)"),bufl,sizeof(buf)-1);
922 if (verbose>=2) error(_(".devcmd(send=%s,term=%s,catch=%s,timeout=%ld)"),
923 reform(buf,0),reform(term,1),reform(catch,2),alarmtime);
924 if (osend) buf[l]='\r';
925 for (offs=0,got=0;offs<bufl;offs++) {
927 usleep((offs?chartimen:cmdtimen)*1000);
928 if (!offs && tcflush(devfd,TCIOFLUSH))
929 error(_("^Error flushing I/O queue of device"));
930 if (write(devfd,buf+offs,1)!=1) break;
933 error(_("^Error forcing output of char at pos %d of cmd %s"),offs,reform(buf,0));
937 error(_("^Wrote only %d of %d bytes of command"),got,bufl);
942 if (!(terml=strlen(term))) {
947 catchl=strlen(catch);
948 fragl=MAX(terml,catchl);
951 fragl=MAX(fragl,MAX(strlen(ERROR_SUBSTR1),strlen(ERROR_SUBSTR2)));
955 edata=(noconvcr?'\r':'\n');
964 got=read(devfd,buf+bufl,sizeof(buf)-1-bufl);
965 if (got==-1 && errno==EAGAIN) {
968 got=read(devfd,buf+bufl,1);
971 if (wasalarm) error(_("Maximum response timeout (%lds) exceeded"),alarmtime);
972 else error(_("^Couldn't read device data (ret=%d)"),got);
979 while (buf+bufl2>s && (s=memchr(s,'\0',buf+bufl2-s))) *s++=REPL_NULLCHAR;
981 error(_("\nGot chunk of data from device: %s"),reform(buf+bufl,0));
984 while (buf+bufl2>s && (s=memchr(s,'\r',buf+bufl2-s))) *s++='\n';
987 catched(buf+bufl,edata); assert(!record || record==buf+bufl);
988 assert(bufl<sizeof(buf)-1);
990 assert(strlen(buf)==bufl);
991 /* d3(">%s|%s<\n",buf,term); */
992 if (strstr(buf,ERROR_SUBSTR1) || strstr(buf,ERROR_SUBSTR2)) {
993 error(_("Found ERROR response on command %s"),reform(send,0));
996 if (catch && !record && bufl>=catchl && (hit=strstr(buf,catch))) {
998 catched(buf+bufl,edata); assert(!record || record==buf+bufl);
1000 if ( bufl>= terml && (hit=strstr(buf,term))) {
1001 memmove(buf,hit+terml,(bufl2=(buf+bufl)-(hit+terml))); bufl=bufl2;
1004 if (bufl<fragl) continue;
1005 memmove(buf,buf+bufl-(fragl-1),(bufl2=fragl-1)); bufl=bufl2;
1006 if (record) record=buf+fragl-1;
1010 if (!catch) return("");
1011 error(_("Data requested on command %s but no found after term %s"),reform(send,0),reform(term,1));
1016 catched(record+1,edata);
1017 if (verbose>=2) error(_(".Returning data %s for cmd %s"),reform(catchdata,0),reform(send,1));
1021 static int prepaddr(unsigned char *d,const char *addr)
1027 if ((plus=(*addr=='+'))) addr++;
1028 *++d=(plus?ADDR_INT:ADDR_NAT);
1030 if (*addr<'0' || *addr>'9')
1031 error(_("!Error during conversion of number at: %s"),addr);
1034 if ((flip=!flip)) *++d=0xF0|n;
1035 else *d=(*d&0x0F)|(n<<4U);
1040 static char *finalsmsc;
1041 #define SMSCBINSIZE (1+1+(MAXNUMLEN+1)/2)
1042 static char pdusmsc[SMSCBINSIZE*2+1];
1044 static inline char tohex(unsigned char x)
1047 if (x<10) return(x +'0');
1051 static inline void textconv(char *d,unsigned char *s,size_t len)
1061 static inline void smscset(void)
1063 char *s,*t,*e,*serr;
1065 unsigned char bin[2+(MAXNUMLEN+1)/2];
1067 if (smsc) devcmd(NULL,NULL,"\r\nAT+CSCA=\"%s\"",smsc);
1068 s=devcmd(NULL,"\n+CSCA:","\r\nAT+CSCA?");
1069 while (isspace(*s)) s++;
1070 if (!*s || !strcmp(s,"EMPTY"))
1071 error(_("!No SMSC set in mobile station found, please use option \"-s\""));
1072 if (verbose>=1) error(_("\nFound default SMSC in mobile: %s"),s);
1073 if (*s!='"') error(_("!No left-quote found in: %s"),s);
1074 if (!(t=strrchr(s+1,'"'))) error(_("!No right-quote found in: %s"),s);
1076 error(_("!No SMS set in mobile station found, please use option \"-s\""));
1078 while (isspace(*t)) t++;
1079 if (*t++!=',') error(_("!No comma found after quotes in: %s"),s);
1080 while (isspace(*t)) t++;
1081 l=strtol(t,&serr,10);
1082 if ((l!=ADDR_NAT && l!=ADDR_INT) || (serr && *serr))
1083 error(_("!Type parse error in: %s"),s);
1084 if (l==ADDR_NAT || s[1]=='+') s++;
1087 if (verbose>=2) error(_("\nDecoded SMSC address: %s"),s);
1088 if (!NEED_PDUSMSC()) return;
1089 chk(finalsmsc=strdup(s));
1090 bin[0]=1+(prepaddr(bin,finalsmsc)+1)/2;
1091 textconv(pdusmsc,bin,bin[0]+1);
1094 static inline unsigned char charconv_send(char c,size_t offs)
1097 case '@': return(0);
1098 case '$': return(2);
1104 if ((c>='A' && c<='Z') || (c>='a' && c<='z') || (c>='0' && c<='9')) return(c);
1105 error(_("Can't convert character '%c' (0x%02X) at offs %d (0-based), substituted '?'"),
1106 c,(unsigned char)c,offs);
1111 static inline unsigned char charconv_recv(char c,size_t offs)
1112 { /* FIXME: unify with charconv_send() */
1114 case 0: return('@');
1115 case 2: return('$');
1119 /* strict checking not done, see charconv_send */
1122 /* Logo format shamelessly stolen from GNokii-0.3.0: http://www.gnokii.org/
1123 * Beware - Nokia Smart Messaging specification 1.0.0 and 2.0.0 is incompatible
1124 * with Nokia current product line implementation
1125 * http://www.forum.nokia.com/developers/smartmsg/download/ssm2_0_0.pdf
1128 static char *pdudata;
1129 static struct hexdata {
1130 struct hexdata *next;
1132 } *hexdata,**hexdatatail=&hexdata;
1134 static void nokiaprep(unsigned char *bin,size_t w)
1138 chk(hd=malloc(sizeof(*hd)));
1141 hexdatatail=&hd->next;
1142 textconv(hd->data,bin,w);
1143 if (verbose>=2) error(_("\nWill send hexdata: %s"),hd->data);
1146 static inline void logoread(void)
1149 char buf[32+140*8+1];
1150 unsigned char bin[140]={
1151 0x06, /* UDH length */
1154 0x15, 0x83, /* dest port (group gfx) */
1155 0x00, 0x00 /* src port (unused) */
1157 size_t got,r=0 /* GCC happiness */,w;
1160 int sizex,sizey,bit;
1162 #define WORD(n) (((unsigned char)buf[(n)])|(((unsigned char)buf[(n)+1])<<8))
1164 if (!(f=fopen(logoname,"rb")))
1165 error(_("^!Cannot open logo file \"%s\" for r/o"),logoname);
1166 got=fread(buf,1,sizeof(buf),f);
1167 chkfclose(f,logoname);
1168 if (got>=20 && !memcmp(buf,"NOL",4)) {
1169 VARPRINTF2(gsmnetf,"%03.3u%02.2u",WORD(6),WORD(8));
1170 assert(strlen(gsmnetf)==5);
1172 if (verbose>=1) error(_(".Reading NOL file \"%s\", GSMnet \"%s\", word@4=%d.."),
1173 logoname,gsmnetf,WORD(4));
1175 else if (got>=16 && !memcmp(buf,"NGG",4)) {
1177 if (verbose>=1) error(_(".Reading NGG file \"%s\", word@4=%d.."),
1180 else error(_("!Unknown file format of logo file \"%s\""),logoname);
1181 if (gsmnet && !strtrycasecmp(gsmnet,WORD_NET)) {
1182 if (!*gsmnetf) error(_("!NOL network code detection requested but NOL file not loaded, please specify network code"));
1185 if (!gsmnet || !strtrycasecmp(gsmnet,WORD_GROUP) || !*gsmnet) {
1186 error(_("\nSending logo as: group graphics"));
1190 error(_("\nSending logo as: operator logo for \"%s\""),gsmnet);
1191 bin[4]=0x82; /* dest port 0x1582 */
1194 sizex=WORD(r); sizey=WORD(r+2);
1195 if (verbose>=2) error(_(".Magic words: @+4=%d, @+6=%d, @+8=%d"),
1196 WORD(r+4),WORD(r+6),WORD(r+8));
1198 if (sizex<1 || sizex>255
1199 || sizey<1 || sizey>255) error(_("!Invalid size: %dx%d"),sizex,sizey);
1200 chars=((bits=sizex*sizey)+7)/8;
1201 if (r+bits>got) error(_("!Logo file \"%s\" too short - actual=%d, need(%dx%d)=%d"),
1202 logoname,got,sizex,sizey,r+chars);
1203 else if (r+bits<got)
1204 if (verbose>=1) error(_("Ignoring trailing garbage in \"%s\", used only %d bytes"),logoname,r+bits);
1205 if ((got=(7+(gsmnet?3:0)+4+chars))>140)
1206 error(_("!SMS size would be %d bytes but 140 is maximum"),got);
1209 bin[w++]=((gsmnet[1]&0x0F)<<4)|(gsmnet[0]&0x0F);
1210 bin[w++]=0xF0 |(gsmnet[2]&0x0F);
1211 bin[w++]=((gsmnet[4]&0x0F)<<4)|(gsmnet[3]&0x0F);
1213 bin[w++]=0x00; /* RFU by Nokia */
1214 bin[w++]=sizex; bin[w++]=sizey;
1215 bin[w++]=0x01; /* one B/W plane */
1218 for (bit=0x80;(bits>0) && (bit>0);bits--,bit>>=1) {
1219 if (buf[r]!='0' && buf[r]!='1')
1220 error(_("!Invalid character (neither '0' nor '1') in logo file \"%s\" at offset 0x%X"),
1222 if (buf[r++]=='1') bin[w]|=bit;
1226 assert(chars==-1); assert(bits==0); assert(w==got);
1231 static inline void ringread(void)
1234 unsigned char bin1[140]={
1238 0x15, 0x81, /* dest port (ring tones) */
1239 0x15, 0x81 /* src port (unused) */
1240 #define BIN1_PAYLOAD (140-7)
1242 unsigned char binn[140]={
1243 11, /* UDH length */
1246 0x15, 0x81, /* dest port (ring tones) */
1247 0x15, 0x81, /* src port (unused) */
1248 0x00, 0x03, /* multipart */
1249 /* 0x??, unique serial ID */
1250 /* 0x??, total messages */
1251 /* 0x??, message number (# from 1) */
1252 #define BINN_PAYLOAD (140-12)
1258 #define WORD(n) (((unsigned char)buf[(n)])|(((unsigned char)buf[(n)+1])<<8))
1260 if (!(f=fopen(ringname,"rb")))
1261 error(_("^!Cannot open ring file \"%s\" for r/o"),ringname);
1262 if ((size=getfilesize(f,ringname))==-1)
1263 error(_("!File size determination is essential to continue operation"));
1265 error(_("!File \"%s\" size %ld too small (must >=0x103)! Is it .000 file?"),
1267 if (fseek(f,0x100,SEEK_SET))
1268 error(_("^Seeking error on \"%s\", ignoring"),ringname);
1270 if (size<=BIN1_PAYLOAD) {
1271 if ((got=fread(bin1+7,1,size,f))!=size)
1272 error(_("^Read error on \"%s\", wanted %ld, got %d"),ringname,size,got);
1273 error(_("\nSending ring tone \"%s\" as single SMS (size %ld, max %d)"),
1274 ringname,size,BIN1_PAYLOAD);
1275 nokiaprep(bin1,7+size);
1278 totn=(size+BINN_PAYLOAD-1)/BINN_PAYLOAD;
1280 error(_("!File size %ld too large even for multi-SMS ring upload (max=%d)"),
1281 size,BINN_PAYLOAD*0xFF);
1284 error(_("\nSending ring tone \"%s\" as %d multi-SMSes (size %ld, max %d, frag %d)"),
1285 ringname,totn,size,BIN1_PAYLOAD,BINN_PAYLOAD);
1286 binn[9]=time(NULL)&0x100; /* rand() would be better but it is a compatibility pain */
1288 error(_("\nUsing unique multi-SMS ID 0x%02X"),(unsigned)binn[9]);
1289 for (fragn=1;fragn<=totn;fragn++) {
1291 want=MIN(size,BINN_PAYLOAD);
1292 if ((got=fread(binn+12,1,want,f))!=want)
1293 error(_("^Read error on \"%s\", wanted %d, got %d"),ringname,want,got);
1294 nokiaprep(binn,12+want);
1298 chkfclose(f,ringname);
1302 static inline void genpdu(void)
1304 static unsigned char pdu[64+MAXNUMLEN/2+(MAXBODYLEN*7)/8];
1305 unsigned char *d=pdu;
1307 char inb=0,outb=0,xb,*bodyr;
1308 unsigned char inreg=0 /* GCC happiness */;
1313 i=prepaddr(d,phone);
1314 *d=i; d+=1+1+(i+1)/2;
1318 if (bodylen>MAXBODYLEN) {
1319 error(_("Body too large (%d>%d), cut"),bodylen,MAXBODYLEN);
1320 body[(bodylen=MAXBODYLEN)]='\0';
1324 assert(d<pdu+sizeof(pdu));
1325 while (bodylen || inb) {
1327 assert(bodylen>0); assert(!!*body);
1328 inreg=charconv_send(*bodyr++,offs++);
1338 d4("inb=%d,outb=%d,xb=%d\n",inb,outb,xb);
1340 *d|=((inreg>>(unsigned)(7-inb))&((1<<xb)-1))<<(unsigned)(8-outb);
1344 assert(d<pdu+sizeof(pdu));
1345 pdudata=malloc(2*(d-pdu)+1);
1346 textconv(pdudata,pdu,d-pdu);
1349 static inline void preparebody(void)
1351 FILE *fin=NULL /* GCC happiness */;
1354 if (body && readbody) {
1366 error(_("\nPlease enter the SMS text body, end with EOF (ctrl-D):"));
1369 if (!(fin=fopen(finame,"rt")))
1370 error(_("^!Can't open data file \"%s\" for r/o"),finame);
1372 chk(body=malloc(BODYLOAD));
1373 bodylen=fread(body,1,BODYLOAD,fin);
1375 error(_("^!Error reading stream \"%s\""),(finame?finame:_("<stdin>")));
1377 chkfclose(fin,finame);
1382 static int datawait(char immed)
1387 #else /* HAVE_POLL */
1389 #endif /* HAVE_POLL */
1399 i=poll(&ufd,1,(immed?0:-1));
1400 #else /* HAVE_POLL */
1401 #ifdef HAVE_FD_SETSIZE
1402 if (devfd>=FD_SETSIZE)
1403 error(_("!Device file descriptor %d can't fit in select() FD_SETSIZE (%d)"),
1405 #endif /* HAVE_FD_SETSIZE */
1406 FD_ZERO(&rfds); FD_SET(devfd,&rfds);
1407 FD_ZERO(&xfds); FD_SET(devfd,&xfds);
1408 i=select(devfd+1,&rfds,NULL,&xfds,NULL);
1409 #endif /* HAVE_POLL */
1410 if (immed && i==0) return(0);
1412 error(_("^Failed (retval %d) while waiting for data, ignoring"),i);
1415 if (ufd.revents&(POLLERR|POLLHUP))
1416 #else /* HAVE_POLL */
1417 if (FD_ISSET(devfd,&xfds))
1418 #endif /* HAVE_POLL */
1419 error(_("^Error while waiting for data, ignoring"));
1422 if (!(ufd.revents&POLLIN))
1423 #else /* HAVE_POLL */
1424 if (!(FD_ISSET(devfd,&rfds)))
1425 #endif /* HAVE_POLL */
1427 error(_("^No data input after waited for data, retrying"));
1433 static char *check_format(const char *fmt,const char *string)
1435 static char err[LINE_MAX],sub[50];
1439 for (sf=fmt,ss=string;(cf=*sf) && (cs=*ss);sf++,ss++) {
1445 if (isdigit(cs)) break;
1449 if (cs=='+' || cs=='-') break;
1454 VARPRINTF(sub,"'%c'",cf); subp=sub;
1456 if (!subp) continue;
1457 VARPRINTF5(err,_("Expected %s, found '%c' at pos %d of string [%s], formatstring [%s]"),
1458 subp,cs,ss-string,string,fmt);
1462 VARPRINTF2(err,_("String too short for format, string [%s], formatstring [%s]"),
1467 VARPRINTF2(err,_("Trailing garbage in string [%s], formatstring [%s]"),
1474 static char *receive_number,*receive_smsc;
1475 static time_t receive_time;
1478 static const struct {
1484 #define TP_ENT(a,b,c,d,e) { a,offsetof(struct tm,b),c,d,e }
1485 TP_ENT( 3,tm_year,0,99,N_("year")),
1486 TP_ENT( 6,tm_mon ,1,12,N_("month")),
1487 TP_ENT( 9,tm_mday,1,31,N_("day of month")),
1488 TP_ENT(12,tm_hour,0,23,N_("hour")),
1489 TP_ENT(15,tm_min ,0,59,N_("minute")),
1490 TP_ENT(18,tm_sec ,0,59,N_("second")),
1491 /* Time zone ignored */
1493 #define GETTIME(i) (*(int *)(((char *)&tm)+timeparse[(i)].tmpos))
1495 static void maketime(const char *string)
1500 for (i=0;i<NELEM(timeparse);i++) {
1502 if (val<timeparse[i].min || val>timeparse[i].max) {
1503 error(_("Weird value of %s, is %d but expected %d..%d, setting to %d"),
1504 _(timeparse[i].name),val,timeparse[i].min,timeparse[i].max,timeparse[i].min);
1505 GETTIME(i)=timeparse[i].min;
1508 if (tm.tm_year<70) tm.tm_year+=100;
1510 d7("mktime(y%dm%dd%dh%dm%ds%d)\n",
1511 tm.tm_year,tm.tm_mon,tm.tm_mday,tm.tm_hour,tm.tm_min,tm.tm_sec);
1512 if ((receive_time=mktime(&tm))==-1)
1513 error(_("^mktime(3) failed for %s"),string);
1516 /* +CMT: "+420602431329",,"99/10/25,03:21:03-00" */
1517 static int receive_headerparse(char *buf)
1522 #define DIGIT2ASC(s) (((s)[0]-'0')*10+((s)[1]-'0'))
1524 for (s=buf;*s==' ';s++);
1526 error(_("Cannot find initial '\"' in CMT header: %s"),buf);
1529 for (s1=s;*s && *s!='"';s++);
1531 error(_("Only one '\"' found in CMT header: %s"),buf);
1534 free(receive_smsc); receive_smsc=NULL;
1535 free(receive_number);
1536 chk(receive_number=malloc(s-s1+1));
1537 memcpy(receive_number,s1,s-s1); receive_number[s-s1]='\0';
1539 if ((err=check_phone(receive_number)) ||
1540 (err=check_format(",,\"99/99/99,99:99:99+99\"",s))) {
1541 error(_("%s in CMT header: %s"),err,buf);
1544 memset(&tm,0,sizeof(tm)); /* may be redundant */
1545 for (i=0;i<NELEM(timeparse);i++)
1546 GETTIME(i)=DIGIT2ASC(s+timeparse[i].strpos);
1547 if (tm.tm_year<70) tm.tm_year+=100;
1554 static void receive_text(char *bodyline)
1556 char *buf,*s,*s1,*s2,*s3;
1562 d2("receive_text: %s\n",bodyline);
1568 if (pid>0) return; /* parent context */
1570 error(_("Can't fork(2), process spawning may block receive"));
1572 else { /* child process */
1578 s1=strchr(s1+(s1!=s),'%');
1579 } while (s1 && s1[1]!='p' && s1[1]!='T' && s1[1]!='t' && s1[1]!='s');
1581 pushargstack_one(s,0);
1585 pushargstack_one(s,0);
1590 pushargstack_one(receive_number,0);
1593 VARPRINTF(tbuf,"%ld",receive_time);
1594 pushargstack_one(tbuf,0);
1597 if (receive_time==-1) break;
1598 if (!(s2=ctime(&receive_time))) {
1599 error(_("Failing ctime(3), ignoring substitution"));
1602 if ((s3=strchr(s2,'\n'))) *s3='\0';
1603 pushargstack_one(s2,0);
1606 if (receive_smsc) pushargstack_one(receive_smsc,0);
1611 buf=glueargstack(NULL,NULL); assert(buf);
1612 if (!(f=popen(buf,"w"))) {
1613 error(_("^Failing spawn of receive command: %s"),buf);
1616 if (fputs(bodyline,f)<0 || putc('\n',f)!='\n')
1617 error(_("^Failing write to child receive command: %s"),buf);
1619 error(_("^Spawned receive command failure (code %d): %s"),i,buf);
1622 if (pid==-1) return;
1623 exit(EXIT_SUCCESS); /* cleanup() has been disabled */
1626 static inline unsigned char fromhex(char c)
1629 return(c<'A'?c-'0':(c-'A')+0xA);
1632 static int teldecode(char *text,unsigned char *bin,size_t digits)
1637 for (i=0;i<digits;text++,i++) {
1652 static void sctsparse(unsigned char *bin,const char *pduline,int offs)
1654 #define DIGIT2BIN(v) (((v)&0x0F)*10+(((v)>>4)&0x0F))
1658 memset(&tm,0,sizeof(tm)); /* may be redundant */
1659 for (i=0;i<NELEM(timeparse);offs++,i++) {
1660 if ((*bin&0x0F)>0x09 || (*bin&0xF0)>0x90) {
1661 error(_("Invalid value of \"%s\" at offset %d in: %s"),
1662 timeparse[i].name,offs,pduline);
1665 GETTIME(i)=DIGIT2BIN(*bin);
1673 static void receive_pdu(char *pduline)
1675 unsigned char pdu[140+0x100],*pdup,*pdue,oalen,inreg;
1676 char text[160+1],*textp,*s;
1677 size_t pdulinel=strlen(pduline),want;
1681 d2("receive_pdu: %s\n",pduline);
1682 if (pdulinel>2*sizeof(pdu))
1683 { error(_("PDU too long (%d/2) to be valid: %s"),pdulinel,pduline); return; }
1685 { error(_("PDU length odd (%d): %s"),pdulinel,pduline); return; }
1687 { error(_("PDU length %d too small (min. 2*%d): %s"),pdulinel,13,pduline); return; }
1688 for (pdup=pdu;*pduline;pduline+=2) {
1689 if (!isxdigit(pduline[0]) || !(isxdigit(pduline[1])))
1690 { error(_("Invalid hex byte: %c%c on byte %d in: %s"),
1691 pduline[0],pduline[1],pdup-pdu,pduline); return; }
1692 *pdup++=(fromhex(pduline[0])<<4)|fromhex(pduline[1]);
1701 { error(_("SMSC length too large (%d, max. %d): %s"),*pdu,10,pduline); return; }
1702 chk(receive_smsc=malloc(1+2*(*pdu)+1));
1704 if (pdu[1]==ADDR_INT) *s++='+';
1706 if (pdu[1]!=ADDR_NAT)
1707 error(_("Unknown address type 0x%02X of %s, ignoring in PDU: %s"),pdu[1],_("SMSC"),pduline); return;
1709 if (teldecode(s,pdu+2,2*(*pdu-1)-((pdu[1+(*pdu)]&0xF0)==0xF0)))
1710 error(_("Some digits unrecognized in %s \"%s\", ignoring in PDU: %s"),_("SMSC"),receive_smsc,pduline);
1713 if (*pdup&0x03) /* PDU type */
1714 error(_("Unrecognized PDU type 0x%02X at offset %d, dropping: %s"),*pdup,pdup-pdu,pduline);
1716 free(receive_number);
1717 if ((oalen=*pdup++)>10) /* OA len */
1718 { error(_("Originating number too large (%d, max. %d): %s"),oalen,10,pduline); return; }
1719 if (pdup+(want=1+(oalen+1)/2+10)>pdue)
1720 { error(_("PDU length too short (want %d, is %d): %s"),(pdup-pdu)+want,pdue-pdu,pduline); return; }
1721 chk(receive_number=malloc(1+2*(*pdup)+1));
1723 if (*pdup==ADDR_INT) *s++='+';
1725 if (*pdup!=ADDR_NAT)
1726 error(_("Unknown address type 0x%02X of %s, ignoring in PDU: %s"),*pdup,_("originating number"),pduline); return;
1729 if (teldecode(s,pdup,oalen))
1730 error(_("Some digits unrecognized in %s \"%s\", ignoring in PDU at offset %d: %s"),
1731 _("originating number"),receive_number,pdup-pdu,pduline);
1733 if (*pdup) /* PID */
1734 error(_("PID number %02X unsupported, ignoring: %s"),*pdup,pduline);
1736 if (*pdup) { /* DCS */
1737 if ((*pdup&0xF4)==0xF4)
1738 { error(_("DCS 0x%02X indicates 8-bit data, unsupported, dropping: %s"),*pdup,pduline); return; }
1739 error(_("DCS 0x%02X unsupported, will attempt decoding: %s"),*pdup,pduline);
1742 sctsparse(pdup,pduline,pdup-pdu);
1746 if (pdue-pdup>140) {
1747 error(_("PDU data (%d) exceed maximum length of %d bytes, cut: %s"),
1748 pdue-pdup,140,pduline);
1752 if (pdup+udlb>pdue) {
1757 error(_("PDU data length (%d/7->%d/8) longer than data (%d), cut to %d/7->%d/8: %s"),
1758 udl,udlb,pdue-pdup,udl1,udlb1,pduline);
1759 udl=udl1; udlb=udlb1;
1762 error(_("Trailing garbage ignored in PDU data (UDL %d/7->%d/8, got %d) in: %s"),
1763 udl,udlb,pdue-pdup,pduline);
1766 inreg=0; /* GCC happiness */
1773 assert(textp<text+160);
1779 d4("inb=%d,outb=%d,xb=%d\n",inb,outb,xb);
1781 *textp|=((inreg>>(unsigned)(7-inb))&((1<<xb)-1))<<(unsigned)(8-outb);
1784 *textp=charconv_recv(*textp,textp-text);
1796 const char *const msg;
1798 { &maxretry,&maxretryn,"maxretry" },
1799 { &readtime,&readtimen,"readtime" },
1800 { &chartime,&chartimen,"chartime" },
1801 { &cmdtime ,&cmdtimen ,"cmdtime" },
1802 { &baud ,&baudn ,"baud" },
1805 int main(int argc,char **argv)
1808 int i,cmgf=-1 /* GCC happiness */;
1810 speed_t portbaud=0 /* GCC happiness */;
1811 enum modenum argsmode;
1814 if ((s=strrchr((pname=*argv),'/'))) pname=s+1;
1817 /* Initialize the i18n stuff */
1818 bindtextdomain(PACKAGE,LOCALEDIR);
1819 if (!setlocale(LC_ALL,""))
1820 error("Locale not supported by C library");
1821 textdomain(PACKAGE);
1827 error(_("atexit(3) not available at compilation time, device cleanup may be missed"));
1829 signal(SIGTERM,(RETSIGTYPE (*)(int))cleanup);
1830 signal(SIGQUIT,(RETSIGTYPE (*)(int))cleanup);
1831 signal(SIGINT ,(RETSIGTYPE (*)(int))cleanup);
1832 signal(SIGHUP ,(RETSIGTYPE (*)(int))cleanup);
1833 assert(mode==MODE_UNKNOWN);
1834 for (i=0;i<NELEM(longopts);i++) {
1835 if (longopts[i].val<MODE_FIRST) break;
1836 if (!strstr(pname,longopts[i].name)) continue;
1837 if (mode==MODE_UNKNOWN || mode==longopts[i].val) {
1838 mode=longopts[i].val;
1845 processargs(argc,argv,_("<command-line>"));
1846 if ((s=getenv("HOME"))) {
1848 char *buf=malloc(l+50);
1851 strcpy(buf+l,CONFIG_HOME);
1855 readfile(CONFIG_MAIN,1);
1858 error(_(".Detected mode \"%s\" from my program name \"%s\""),MODE_NAME(argsmode),pname);
1860 error(_(".Automatic mode detection unsuccessul for my progam name \"%s\""),pname);
1864 error(_("!Operation mode unset, use --send or similiar command, see help (-h)"));
1865 error(_(".Running program in mode \"%s\""),MODE_NAME(mode));
1868 case MODE_SEND: /* FALLTHRU */
1869 case MODE_SEND_MOBILDOCK: cmdline_send (); break;
1870 case MODE_LOGO_SEND: cmdline_logo_send(); break;
1871 case MODE_RING_SEND: cmdline_ring_send(); break;
1872 case MODE_RECEIVE: cmdline_receive (); break;
1876 for (i=0;i<NELEM(nullcheck);i++) {
1877 const struct nullcheck *n=nullcheck+i;
1879 if (*n->var) continue;
1880 if (n->reqd && !(MODE_BIT(mode)&n->reqd)) continue;
1881 error(_("Missing parameter \"%s\""),_(n->name));
1884 if (fatal) error(_("!Previous %s considered unrecoverable"),(fatal==1?_("error"):_("errors")));
1886 if (!logname) logname=DEF_LOGNAME;
1887 if (!lockfile) lockfile=DEF_LOCKFILE;
1888 if (!device) device=DEF_DEVICE;
1890 for (i=0;i<NELEM(numarg);i++) {
1892 if (!*numarg[i].sp) continue;
1893 *numarg[i].ip=strtol(*numarg[i].sp,&serr,0);
1894 if (*numarg[i].ip<0 || *numarg[i].ip>=LONG_MAX || !serr || *serr)
1895 error(_("!Number parse error for parameter \"%s\" of \"%s\" at: %s"),
1896 numarg[i].msg,*numarg[i].sp,serr);
1899 readtimen=(mode==MODE_SEND_MOBILDOCK?DEF_READTIME_MOBILDOCK:DEF_READTIME);
1900 if (mode==MODE_SEND_MOBILDOCK) mode=MODE_SEND;
1902 if (!strchr(device,'/')) {
1903 size_t l=strlen(device);
1904 chk(s=malloc(5+l+1));
1910 devicename=strrchr(device,'/')+1; assert(!!(devicename-1));
1911 for (i=0,s=lockfile;*s;s++) {
1912 if (*s!='%') continue;
1914 if (*s=='%') continue;
1916 if (i) error(_("!Only one \"%%s\" permitted in lockfile format-string"));
1919 error(_("!Invalid format-character '%c' in lockfile format-string, only \"%%s\" allowed"),*s);
1923 if (!(logf=fopen(logname,"a")))
1924 error(_("^!Error opening log \"%s\" for append"),logname);
1925 logmsg(_("Starting up: %s"),PACKAGE " " VERSION);
1934 case MODE_LOGO_SEND:
1937 case MODE_RING_SEND:
1940 case MODE_RECEIVE: break;
1944 error(_("Warning: -f / --file is forbidden with mode \"%s\""),MODE_NAME(mode));
1947 case 2400: portbaud= B2400; break;
1948 case 4800: portbaud= B4800; break;
1949 case 9600: portbaud= B9600; break;
1950 case 19200: portbaud=B19200; break;
1951 case 38400: portbaud=B38400; break;
1952 case 57600: portbaud=B57600; break;
1954 error(_("!Specified baudrate %ld is not supported"),baudn);
1956 if (verbose>=2) error(_(".Will use baudrate %ld with hexval 0x%X"),baudn,portbaud);
1958 if (lockfile && *lockfile && VARPRINTF(lockreal,lockfile,devicename)>0) {
1960 if (verbose>=1) error(_(".Locking device \"%s\" by \"%s\".."),device,lockreal);
1964 if ((end-=start)>LOCKREPORT)
1965 logmsg(_("Device lock succeeded after %ld seconds"),(long)end);
1967 if (verbose>=1) error(_(".Opening device \"%s\".."),device);
1968 if ((devfd=open(device,O_RDWR|O_NDELAY))<0)
1969 error(_("^!Cannot open device \"%s\" for r/w access"),device);
1971 if (tcgetattr(devfd,&restios))
1972 error(_("^Unable to get termios settings"));
1974 restios.c_cflag=(restios.c_cflag&~(CBAUD|CBAUDEX))|B0|HUPCL;
1977 tios.c_iflag=IGNBRK|IGNPAR|IXON|IXOFF;
1979 tios.c_cflag=CS8|CREAD|CLOCAL|HUPCL|portbaud;
1980 tios.c_lflag=IEXTEN|NOFLSH;
1981 memset(tios.c_cc,_POSIX_VDISABLE,sizeof(tios.c_cc));
1984 cfsetispeed(&tios,portbaud);
1985 if (cfsetospeed(&tios,portbaud)|cfsetispeed(&tios,portbaud))
1986 error(_("^Error setting termios baudrate on device"));
1987 if (tcflush(devfd,TCIOFLUSH))
1988 error(_("^Error flushing termios (TCIOFLUSH) on device"));
1989 if (tcsetattr(devfd,TCSANOW,&tios))
1990 error(_("^!Unable to set initial termios device settings"));
1995 devcmd("",NULL,"\r\nAT\033\032"); /* ESCAPE, CTRL-Z */
1996 devcmd(NULL,NULL,"\r\nAT");
1998 if (mode==MODE_SEND || mode==MODE_RECEIVE) {
2001 if (!devcmd(NULL,NULL,"!\r\nAT+CMGF=0")) {
2002 if (!devcmd(NULL,NULL,"!\r\nAT+CMGF=1"))
2003 { retrying(); continue; }
2006 error(_(".Using AT+CMGF=1 (text mode).."));
2012 error(_(".Using AT+CMGF=0 (PDU mode).."));
2020 devcmd("\n> ",NULL,"\r\nAT+CMGS=\"%s\"",phone);
2021 s=devcmd(NULL,"\n+CMGS:","!~%s\032",body);
2024 devcmd("\n> ",NULL,"\r\nAT+CMGS=%d",(strlen(pdusmsc)+strlen(pdudata))/2);
2025 s=devcmd(NULL,"\n+CMGS:","!~%s%s\032",pdusmsc,pdudata);
2028 case MODE_LOGO_SEND:
2029 case MODE_RING_SEND: {
2032 restore="\r\nAT+CSMP=17,,0,0";
2033 devcmd(NULL,NULL,"\r\nAT+CSMP=81,,0,245");
2034 while ((hd=hexdata)) {
2035 devcmd("\n> ",NULL,"\r\nAT+CMGS=\"%s\"",phone);
2036 if (!(s=devcmd(NULL,"\n+CMGS:","!~%s\032",hd->data))) break;
2037 if ((hexdata=hd->next)) pushargstack_one(s,0);
2043 restore="\r\nAT+CNMI=,0";
2044 devcmd(NULL,NULL,"\r\nAT+CNMI=,2");
2045 devcmd(NULL,NULL,"\r\nAT+CSDH=0");
2047 /* Never bail-out when we got up to this point */
2048 if (maxretryn!=-1 && verbose>=1)
2049 error(_(".Initialization successful, infinite retry count set"));
2052 receive_headerparse(" \"+420602123456\",,\"99/10/25,03:21:03-00\"");
2053 receive_accept("TESTBODY");
2057 if (!lockdevice(1)) {
2059 error(_(".Dialout detected, waiting for lock.."));
2063 d1("Lock-device succeeded\n");
2065 d1("Reading a message for us...\n");
2066 if (!(s=devcmd("\r","@+CMT:"," ")))
2068 if (cmgf && !(i=receive_headerparse(s)))
2069 error(_("Receive-header parsing failed on: %s"),s);
2070 if (!(s=devcmd("\r","@\n"," ")))
2073 if (i) receive_text(s);
2075 else receive_pdu(s);
2076 if (!devcmd("\n",NULL," ")) /* eat last '\n' */
2078 } while (datawait(1));
2083 if (!s) { retrying(); goto retryall; }
2085 pushargstack_one(s,0); s=NULL;
2086 if (verbose>=1) while ((s=nextargstack())) {
2087 while (isspace(*s)) s++;
2088 error(_("\nMessage successfuly sent with MR (Message Reference): %s"),s);
2090 devcmd(NULL,NULL,"\r\nAT");
2092 logmsg(_("SMS sent (after %d retries), %d part(s)"),retrycnt,parts);
2093 return(EXIT_SUCCESS);