1 #define WANT_DECLARATIONS 1
4 static char rcsid[] ATTR_UNUSED = "$Id$";
39 #ifdef HAVE_SYS_TYPES_H
40 #include <sys/types.h>
42 #ifdef HAVE_SYS_WAIT_H
45 #ifdef HAVE_SYS_STAT_H
57 #ifdef HAVE_SYS_TIME_H
60 #ifdef HAVE_SYS_POLL_H
67 #ifdef HAVE_GETOPT_LONG
74 /* Always override possible system defintions as it is safe (used by glib) */
76 #define MAX(a,b) ((a)>(b)?(a):(b))
78 #define MIN(a,b) ((a)<(b)?(a):(b))
80 #define NELEM(x) (sizeof((x))/sizeof(*(x)))
87 /* ANSI C does not allow macro with variable arguments */
89 #define dB(a) dbg(fprintf a)
91 #define d1(n1) dB((dO,n1 ))
92 #define d2(n1,n2) dB((dO,n1,n2 ))
93 #define d3(n1,n2,n3) dB((dO,n1,n2,n3 ))
94 #define d4(n1,n2,n3,n4) dB((dO,n1,n2,n3,n4 ))
95 #define d5(n1,n2,n3,n4,n5) dB((dO,n1,n2,n3,n4,n5 ))
96 #define d6(n1,n2,n3,n4,n5,n6) dB((dO,n1,n2,n3,n4,n5,n6 ))
97 #define d7(n1,n2,n3,n4,n5,n6,n7) dB((dO,n1,n2,n3,n4,n5,n6,n7 ))
98 #define d8(n1,n2,n3,n4,n5,n6,n7,n8) dB((dO,n1,n2,n3,n4,n5,n6,n7,n8))
100 static const char version[]="Mobile Device SMS tool (" PACKAGE " " VERSION ")\n";
108 static int dis_cleanup=0,devfd=-1;
110 static char *phone,*device,*logname,*lockfile,*smsmode,*pdusmscmode,*smsc,*maxretry,*readtime,*chartime,*cmdtime,*baud,*restore;
112 static long maxretryn=DEF_MAXRETRY,readtimen=-1,chartimen=DEF_CHARTIME,cmdtimen=DEF_CMDTIME,baudn=DEF_BAUD;
114 static int handshake_rtscts;
115 static unsigned handshake_stamp;
117 #define handshake_rtscts (0)
123 } force_smsmode=FSM_AUTO;
129 } force_pdusmscmode=FPSM_AUTO,
130 #define FPSM_MIN (FPSM_COUNT_IN)
131 #define FPSM_MAX (FPSM_NONE)
132 try_pdusmscmode=FPSM_MIN;
133 static size_t bodylen;
134 /* --send / --send-mobildock / --receive specific */
136 /* --logo-send specific */
137 static char *logoname,*gsmnet;
138 /* --ring-send specific */
139 static char *ringname;
140 /* --picture-send specific */
141 static char *picturename;
143 static enum modenum {
145 /* must differ from regular char-s */
147 MODE_SEND =MODE_FIRST+0, /* --send / --send-mobildock */
148 MODE_SEND_MOBILDOCK=MODE_FIRST+1, /* --send-mobildock in before readtimen is set */
149 MODE_RECEIVE =MODE_FIRST+2, /* --receive */
150 MODE_LOGO_SEND =MODE_FIRST+3, /* --logo-send */
151 MODE_RING_SEND =MODE_FIRST+4, /* --ring-send */
152 MODE_PICTURE_SEND =MODE_FIRST+5 /* --picture-send */
154 #define MODE_ORDER(x) ((x)-MODE_FIRST)
155 #define MODE_NAME(x) (longopts[MODE_ORDER((x))].name)
156 #define MODE_BIT(x) (1<<MODE_ORDER((x)))
158 static unsigned mode_stamp;
160 /* pdusmsc variable has to be filled in */
161 #define NEED_PDUSMSC() (mode==MODE_SEND)
163 static char *devicename; /* path stripped */
164 static char lockreal[512],locked;
166 static struct termios restios,tios;
167 static char restios_yes;
170 static void vlogmsg(char pm,char fatal,const char *fmt,va_list ap) ATTR_PRINTFORMAT(3,0);
171 static void vlogmsg(char pm,char fatal,const char *fmt,va_list ap)
181 if (gethostname(host,sizeof(host))) strcpy(host,_("<ERROR>"));
185 if ((s=strchr(ctm,'\n'))) *s='\0';
186 fprintf(logf,"%s %s %s[%d]: ",ctm,host,pname,mypid);
187 vfprintf(logf,fmt,ap);
188 if (pm) { fputs(": ",logf); fputs(strerror(errno),logf); }
189 if (fatal!='\n') fputc((fatal=='.'?'.':'!'),logf);
194 static void logmsg(const char *fmt,...) ATTR_PRINTFORMAT(1,2);
195 static void logmsg(const char *fmt,...)
199 vlogmsg(0,'\n',fmt,ap);
203 static void error(const char *fmt,...) ATTR_PRINTFORMAT(1,2);
204 static void error(const char *fmt,...)
209 if ((pm=(*fmt=='^'))) fmt++;
211 if (fatal=='!' || fatal=='.' || fatal=='\n') fmt++;
214 fprintf(stderr,"%s: ",pname);
216 vfprintf(stderr,fmt,ap);
217 if (fatal=='!') vlogmsg(pm,fatal,fmt,ap);
219 if (pm) { fputs(": ",stderr); fputs(strerror(errno),stderr); }
220 if (fatal!='\n') fputc((fatal=='.'?'.':'!'),stderr);
222 if (fatal=='!') exit(EXIT_FAILURE);
225 static void chk(const void *p)
228 error(_("!Virtual memory exhausted"));
231 static char *devcmd(const char *term,const char *catch,const char *send,...) ATTR_PRINTFORMAT(3,4);
233 static void unlockdevice(int hard)
235 d2("unlockdevice(), locked=%d\n",locked);
236 if (!locked || !*lockreal) return;
237 if (!hard && locked>1) { locked--; return; }
238 d2("Removing lockfile \"%s\"\n",lockreal);
239 if (unlink(lockreal))
240 error(_("^Error removing my device lockfile \"%s\""),lockreal);
244 static void cleanup(void)
247 if (dis_cleanup) return;
251 devcmd(NULL,NULL,"\r\nAT");
252 devcmd(NULL,NULL,cmd);
253 devcmd(NULL,NULL,"\r\nAT");
256 if (tcsetattr(devfd,TCSANOW,&restios))
257 error(_("^Error restoring termios for device"));
265 static void usage(void)
271 Usage: %s [-c|--config <cfgfile>] [-d|--device <device>]\n\
272 [-L|--log <file>] [-l|--lockfile <lock>]\n\
273 [-b|--baud <rate>] [-x|--xonxoff] [-C|--rtscts]\n\
274 [-M|--smsmode <mode>] [-P|--pdusmscmode <mode>]\n\
275 [-s|--smsc <smsc #>] [-m|--maxretry <#>]\n\
276 [-r|--readtime <sec>] [-t|--chartime <msec>] [-T|--cmdtime <msec>]\n\
277 [-v|--verbose] [-h|--help] [-V|--version]\n\
278 {--send | --send-mobildock | --receive | --logo-send}\n\
279 --send / --send-mobildock:\n\
280 [-f|--file] <dest. phone> <msg text|msg filename>\n\
284 <dest. phone> <logo filename> [<GSMnet id>]\n\
286 <dest. phone> <ring filename>\n\
288 <dest. phone> <picture .ras filename>\n\
290 -c, --config\tRead this additional config file\n\
291 \t\t(def. \"%s\" and \"$HOME%s\")\n\
292 -d, --device\tMobile on this serial device (def. \"%s\")\n\
293 -L, --log\tLog all important messages to this file (def. \"%s\")\n\
294 -l, --lockfile\tLock serial port by this file, \"%%s\" is basename of device\n\
296 -b, --baud\tSet baudrate, 2400-57600 supported (def. %d)\n\
297 -x, --xonxoff\tUse XON/XOFF (AKA software) serial port handshaking - default\n\
298 -C, --rtscts\tUse RTS/CTS (AKA hardware) serial port handshaking%s\n\
299 -M, --smsmode\tForce SMS as: \"pdu\" or 0: PDU mode, \"text\" or 1: text mode\n\
300 -P, --pdusmscmode\tForce PDU as: \"count-in\", \"count-out\", \"none\"\n\
301 -s, --smsc\tUse this SMS Center number (def. query from mobile)\n\
302 -m, --maxretry\tMaximum retries of any command before giving up (def. %d)\n\
303 -r, --readtime\tSeconds for maximum wait time for response\n\
304 \t\t(def. %ds standard, %ds for MobilDock modes,\n\
305 \t\t multiplied %dx for long cmds)\n\
306 -t, --chartime\tMilliseconds between each char (def. %dms)\n\
307 -T, --cmdtime\tMilliseconds before each whole AT command (def. %dms)\n\
308 -v, --verbose\tIncrease verbosity level, more \"-v\"s give more messages\n\
309 -h, --help\tPrint a summary of the options\n\
310 -V, --version\tPrint the version number\n\
312 --send / --send-mobildock:\n\
313 -f, --file\tRead contents of message from file instead\n\
315 <command name>\tProgram to run on receive, message will be on stdin\n\
316 \t\tFollowing substitutes are recognized:\n\
317 \t\t%%p - source phone number\n\
318 \t\t%%T - timestamp from SMSC as # of seconds from 1970 (-1 if invalid)\n\
319 \t\t%%t - ctime(3) style timestamp (e.g. \"Wed Jun 30 21:49:08 1993\"),\n\
320 \t\t empty string if invalid\n\
321 \t\t%%s - originating SMSC number, if available (else empty)\n\
323 <GSMnet id>\t* Oper. logo: Enter custom network code MccMnc, e.g. 23002\n\
324 \t\t* Oper. logo: Specify \"%s\" to read network code from NOL file\n\
325 \t\t* Group gfx : Specify \"%s\" to send logo as group graphics\n\
327 You may need to use the following line to catch all of this help text:\n\
328 ./mdsms -h 2>&1|more\n\
329 \n"),version,PACKAGE,CONFIG_MAIN,CONFIG_HOME,DEF_DEVICE,DEF_LOGNAME,DEF_LOCKFILE,DEF_BAUD,
333 _("\n\t\t(Not supported on this platform!)"),
335 DEF_MAXRETRY,DEF_READTIME,DEF_READTIME_MOBILDOCK,EXT_READTIME,DEF_CHARTIME,DEF_CMDTIME,
336 WORD_NET,WORD_GROUP);
340 static const struct option longopts[]={
341 /* Modes has to be in-order on exact positions */
342 {"send" ,0,0,MODE_SEND},
343 {"send-mobildock",0,0,MODE_SEND_MOBILDOCK},
344 {"receive" ,0,0,MODE_RECEIVE},
345 {"logo-send" ,0,0,MODE_LOGO_SEND},
346 {"ring-send" ,0,0,MODE_RING_SEND},
347 {"picture-send" ,0,0,MODE_PICTURE_SEND},
348 /* Mode aliases may follow in no particular order *
349 * as long as no non-mode options is between them */
350 {"send-md" ,0,0,MODE_SEND_MOBILDOCK},
351 {"recv" ,0,0,MODE_RECEIVE},
352 {"logo" ,0,0,MODE_LOGO_SEND},
353 {"ring" ,0,0,MODE_RING_SEND},
354 {"picture" ,0,0,MODE_PICTURE_SEND},
358 {"lockfile" ,1,0,'l'},
360 {"xonxoff" ,0,0,'x'},
362 {"smsmode" ,1,0,'M'},
363 {"pdusmscmode" ,1,0,'P'},
365 {"maxretry" ,1,0,'m'},
366 {"readtime" ,1,0,'r'},
367 {"chartime" ,1,0,'t'},
368 {"cmdtime" ,1,0,'T'},
370 {"verbose" ,0,0,'v'},
372 {"version" ,0,0,'V'},
375 static void processargs(int argp,char **args,const char *from);
377 static char *cfgstack[MAXCFGLOOP];
378 static unsigned cfgstacki=0;
380 static void chkfclose(FILE *f,const char *fname)
383 error(_("^Error closing \"%s\""),fname);
386 static long getfilesize(FILE *f,const char *fname)
390 if (fseek(f,0,SEEK_END))
391 error(_("^Error seeking to end of \"%s\""),fname);
392 if ((size=ftell(f))<0)
393 size=-1,error(_("^Error measuring length of \"%s\""),fname);
398 static void readfile(const char *fname,char quiet)
402 char *args[MAXCFGARGS],*d,*s,blank,quote;
406 static unsigned tot=0;
408 if (tot++>=MAXCFGNUM) {
409 if (tot==MAXCFGNUM+1) error(_("Too many config files to read, max is %d, break-out"),MAXCFGNUM);
412 if (!(f=fopen(fname,"rt"))) {
413 if (!quiet) error(_("^Can't open config file \"%s\" for r/o"),fname);
417 if (verbose>=2) error(_(".Reading config file \"%s\""),fname);
418 if ((size=getfilesize(f,fname))==-1) size=0;
420 error(_("File \"%s\" is too long, read only %d bytes"),fname,MAXCONFIG);
421 chk(buf=malloc((size?size:MAXCONFIG)+1));
422 got=fread(buf,1,(size?size:MAXCONFIG),f);
423 if (size && got!=size)
424 error(_("File \"%s\" read error, got only %u bytes of %ld"),fname,got,size);
428 for (argp=1,d=s=buf,blank=1,quote=0;s<buf+got;s++) {
431 if (!quote && isspace(c)) {
435 if (verbose>=2) error(_("\nConfig \"%s\": arg#%d: %s"),fname,argp-1,args[argp-1]);
440 if (argp>=NELEM(args)-1) {
441 error(_("Too many arguments in \"%s\", from offset %d ignored"),fname,s-buf);
448 if (c=='\\') { *d++=*++s; continue; }
449 if (c=='"' || c=='\'') {
450 if (!quote ) { quote=c; continue; }
451 if ( quote==c) { quote=0; continue; }
457 processargs(argp,args,fname);
461 static struct argstack {
462 struct argstack *next;
468 static struct argstack **argstack_tail=&argstack;
469 static size_t lastargstack_len;
470 static const char *lastargstack_from;
471 static int lastargstack_index;
473 static size_t argstack_size;
474 static int argstack_num;
476 static void pushargstack(char **args,int num,int offset,const char *from,char stack)
483 chk(as=malloc(sizeof(*as)+sizeof(as->arg)*(num-1)));
486 if (!from) as->from=NULL;
487 else chk(as->from=strdup(from));
488 for (i=0;i<num;i++) {
489 chk(as->arg[i]=strdup(args[i]));
490 argstack_size+=strlen(args[i]);
500 argstack_tail=&as->next;
504 static void pushargstack_one(char *s,char stack)
505 { pushargstack(&s,1,0,NULL,stack); }
507 static char *nextargstack(void)
512 if (argstack && order==argstack->num) {
513 struct argstack *as=argstack;
514 if (!(argstack=as->next))
515 argstack_tail=&argstack;
517 free((char *)as->from);
518 lastargstack_from=NULL;
522 assert(!argstack_num); assert(!argstack_size);
525 assert(order<argstack->num);
526 lastargstack_index=argstack->offset+order;
527 r=argstack->arg[order++];
528 assert(argstack_num>0); argstack_num--;
529 lastargstack_len=strlen(r);
530 assert(argstack_size>=lastargstack_len); argstack_size-=lastargstack_len;
531 lastargstack_from=argstack->from;
535 static char *glueargstack(size_t *destlenp,const char *glue)
537 size_t gluel=(glue?strlen(glue):0),destlen;
541 chk(dest=strdup(""));
542 if (destlenp) *destlenp=0;
545 destlen=argstack_size+(argstack_num-1)*gluel;
546 if (destlenp) *destlenp=destlen;
547 chk(dest=malloc(destlen+1));
548 for (d=dest;(s=nextargstack());) {
549 memcpy(d,s,lastargstack_len);
552 if (!argstack_num) break;
554 memcpy(d,glue,gluel);
556 assert(d<=dest+destlen);
558 assert(!argstack_num);
559 assert(d==dest+destlen);
574 { 'P',&pdusmscmode },
582 static void processargs(int argp,char **args,const char *from)
585 static unsigned seq=0;
589 optarg=NULL; optind=0; /* FIXME: Possible portability problem. */
590 while ((optc=getopt_long(argp,args,"c:d:L:l:b:xCM:P:s:m:r:t:T:fvhV",longopts,NULL))!=EOF) switch (optc) {
592 if (cfgstacki>=NELEM(cfgstack)) {
593 error(_("Looping (%d) during attempt to read config file \"%s\", break-out"),NELEM(cfgstack),from);
596 chk(cfgstack[cfgstacki++]=strdup(optarg));
598 case 'd': case 'L': case 'b': case 'l': case 'M': case 'P': case 's': case 'm': case 'r': case 't': case 'T':
599 for (i=0;i<NELEM(optset);i++)
600 if (optset[i].c==optc) {
601 if (optset[i].stamp && optset[i].stamp!=seq) {
602 assert(!!*optset[i].var);
605 free(*optset[i].var);
606 chk(*optset[i].var=strdup(optarg));
610 assert(i<NELEM(optset));
614 if (handshake_stamp && handshake_stamp!=seq) break;
615 handshake_rtscts=(optc=='C');
619 error(_("!RTS/CTS handshake NOT supported on this platform! Occured during parsing option %d from \"%s\""),optind-1,from);
623 case MODE_SEND_MOBILDOCK:
627 case MODE_PICTURE_SEND:
628 if (mode_stamp && mode_stamp!=seq) break;
636 #ifndef DEBUG /* prevent suppositious overflow */
641 fprintf(stderr,version);
645 error(_("\nLast getopt(3) error occured during parsing option %d from \"%s\"! Follows help:"),optind-1,from);
649 pushargstack(args+optind,argp-optind,optind,from,1);
651 char *s=cfgstack[--cfgstacki];
653 assert(cfgstacki>=0);
656 assert(cfgstacki>=0 && cfgstacki<NELEM(cfgstack));
660 static const struct nullcheck {
665 {&phone,MODE_BIT(MODE_SEND)|MODE_BIT(MODE_SEND_MOBILDOCK)|MODE_BIT(MODE_LOGO_SEND),
666 N_("destination phone number")},
667 {& logoname,MODE_BIT( MODE_LOGO_SEND),N_( "logo filename")},
668 {& ringname,MODE_BIT( MODE_RING_SEND),N_( "ring filename")},
669 {&picturename,MODE_BIT(MODE_PICTURE_SEND),N_("picture filename")},
670 {&body,MODE_BIT(MODE_RECEIVE),N_("body text")}, /* we allow empty bodies for SENDs */
672 {&gsmnet,MODE_BIT(MODE_LOGO_SEND),N_("GSM operator network code")},
673 {&device,0,N_("device for communication")},
676 static char **emptycheck[]={&logname,&smsc,&logoname,&gsmnet};
678 static inline void emptyclean(void)
682 for (i=0;i<NELEM(emptycheck);i++)
683 if (*emptycheck[i] && !**emptycheck[i]) {
684 free(*emptycheck[i]);
689 static inline void cmdline_done(void)
692 while ((s=nextargstack())) {
693 error(_("\nExcessive option %d from \"%s\" ignored: %s"),
694 lastargstack_index,lastargstack_from,s);
700 static char *check_phone(const char *phone)
703 static char err[LINE_MAX];
705 for (s=s1=(phone+(*phone=='+'));*s && s-s1<MAXNUMLEN;s++)
707 VARPRINTF2(err,_("Invalid digit '%c' in phone number - at offset %d"),
711 if (!*s) return(NULL);
712 VARPRINTF2(err,_("Phone number too long (%d), max. %d digits allowed"),
713 strlen(s1),MAXNUMLEN);
717 static void cmdline_phone(void)
719 if (!phone && (phone=nextargstack())) {
722 if ((s=check_phone(phone)))
723 error(_("!%s in option %d from \"%s\": %s"),
724 s,lastargstack_index,lastargstack_from,phone);
728 static inline void cmdline_receive(void)
732 if (!body && argstack_num) {
733 body=glueargstack(&bodylen," ");
734 for (s=body;(s=strchr(s,'%'));s++)
736 case 'p': case 'T': case 't': case 's': break;
738 error(_("Unknown formatsymbol '%c' (use \"%%%%%c\" to fix it) at pos %d in: %s"),
744 static inline void cmdline_send(void)
747 if (!body && argstack_num)
748 body=glueargstack(&bodylen," ");
751 static inline void cmdline_logo_send(void)
756 if (!logoname) logoname=nextargstack();
757 if (!gsmnet && (ogsmnet=nextargstack())) {
760 chk(gsmnet=strdup(ogsmnet));
761 if (strtrycasecmp(gsmnet,WORD_NET) && strtrycasecmp(gsmnet,WORD_GROUP)) {
762 for (d=s=gsmnet;*s;s++) {
763 if (isdigit(*s)) { *d++=*s; continue; }
764 if (isspace(*s)) continue;
765 error(_("\nInvalid characted '%c' in GSMnet at offs %d: %s"),
766 *s,s-gsmnet,ogsmnet);
771 error(_("\nGSMnet is required to have exactly 5 digits or to be\n\
772 either \"%s\" or \"%s\", but found length %d: %s"),
773 WORD_NET,WORD_GROUP,d-gsmnet,ogsmnet);
778 error(_("\nGSMnet option %d from \"%s\" rejected due to previous errors: %s"),
779 lastargstack_index,lastargstack_from,ogsmnet);
787 static inline void cmdline_ring_send(void)
790 if (!ringname) ringname=nextargstack();
793 static inline void cmdline_picture_send(void)
796 if (!picturename) picturename=nextargstack();
799 static void lockclose(int fd)
802 error(_("Error closing lockfile \"%s\""),lockreal);
805 static int lockdevice(int attempt)
814 d2("lockdevice(), locked=%d\n",locked);
815 if (locked) return (++locked);
817 if (fd!=-1) lockclose(fd);
819 if (delay) sleep(delay);
820 delay=DEVLOCK_PERIOD;
821 if (verbose>=3) error(_(".Checking the lockfile \"%s\".."),lockreal);
822 if ((fd=open(lockreal,O_RDONLY))==-1) break;
823 if ((got=read(fd,buf,sizeof(buf)-1))<=0) {
825 if (empty>=DEVLOCK_MAXEMPTY) {
826 error(_(".Lockfile \"%s\" is still not valid, removing it"),lockreal);
832 assert(got<sizeof(buf));
834 if (sscanf(buf,"%d",&pid)!=1) goto isempty;
837 if (kill(pid,0) && errno!=ESRCH && errno!=EPERM)
838 error(_("^Error during checking consciousness of PID %d"),pid);
840 if (attempt) return(0);
843 error(_(".Lockfile \"%s\" is stale (PID %d), removing it"),lockreal,pid);
846 if (unlink(lockreal))
847 error(_("^Error removing foreign lockfile \"%s\""),lockreal);
851 if ((fd=open(lockreal,O_WRONLY|O_CREAT|O_EXCL,0644))==-1) {
852 if (errno==EEXIST) goto recheck;
853 error(_("^!Error creating lockfile \"%s\""),lockreal);
856 got=VARPRINTF(buf,"%010d\n",getpid()); assert(got==11);
857 if (write(fd,buf,got)!=got)
858 error(_("^!Error writing data to lockfile \"%s\""),lockreal);
863 static char wasalarm=0;
864 static void sigalarm(int signo);
866 static void setalarm(void)
868 signal(SIGALRM,(RETSIGTYPE (*)(int))sigalarm);
869 #ifdef HAVE_SIGINTERRUPT
870 siginterrupt(SIGALRM,1);
874 static void sigalarm(int signo)
878 if (verbose>=1) error(_("Timed out"));
881 static void blocking(char yes)
883 static char state=-1;
884 if (state==yes) return;
885 if (fcntl(devfd,F_SETFL,(yes?0:O_NONBLOCK)))
886 error(_("^!fcntl() on device for %s mode"),(yes?_("blocking"):_("non-blocking")));
890 static const char *record,*recordend;
891 static char *catchdata;
892 static size_t catchdatal,catchdatasiz;
894 static const char *reform(const char *s,int slot);
895 static void catched(const char *end,char edata)
902 p=memchr(record,edata,end-record);
903 if ((len=(p?p:end)-record)) {
905 chk(catchdata=malloc((catchdatasiz=LINE_MAX)));
906 if (catchdatal+len>catchdatasiz)
907 chk(catchdata=realloc(catchdata,
908 (catchdatasiz=(catchdatal+len)*2)));
909 memcpy(catchdata+catchdatal,record,len);
912 record =(p?NULL:end);
913 recordend=(p?p :end);
914 assert(catchdatal<=catchdatasiz);
917 static int retrycnt=0;
918 static void retrying(void)
920 if (maxretryn>=0 && ++retrycnt>=maxretryn) error(_("!Maximum command retry count (%ld) exceeded"),maxretryn);
921 if (verbose>=2) error(_(".Retrying phase, %d out of %ld.."),retrycnt,maxretryn);
924 static const char *reform(const char *s,int slot)
926 static struct formslot {
933 assert(slot>=0 && slot<NELEM(arr));
934 if (!s) return(_("<unset>"));
935 if (!(fs=&arr[slot])->s)
936 chk(fs->s=malloc(fs->l=LINE_MAX));
938 for (*d++='"';(c=*s);s++) {
939 if (d>=fs->s+fs->l-10) {
941 chk(fs->s=realloc(fs->s,(fs->l=(fs->l?fs->l*2:LINE_MAX))));
944 if (c!='\\' && c!='"' && isprint(c)) { *d++=c; continue; }
947 case '\\': case '"': *d++=c; break;
948 case '\n': *d++='n'; break;
949 case '\r': *d++='r'; break;
950 case '\032': *d++='Z'; break;
951 case '\033': *d++='e'; break;
953 d+=sprintf(d,"x%02X",(unsigned char)c);
961 static char devcmd_empty_return='\0'; /* returned as catch when only newlines found */
963 static char *devcmd(const char *term,const char *catch,const char *send,...) ATTR_PRINTFORMAT(3,4);
964 static char *devcmd(const char *term,const char *catch,const char *send,...)
966 size_t l,bufl2,terml,catchl=0 /* GCC happiness */,fragl,offs;
967 static char buf[LINE_MAX];
972 char errout,extend,catch_any,edata;
975 static const char emptystring[]="";
978 if (!term) term="\nOK\n";
979 if (!strcmp(send," ")) send=NULL; /* GCC formatstring-check workaround */
980 if (verbose>=2) error(_(".devcmd(sendfmt=%s,term=%s,catch=%s)"),
981 reform(send,0),reform(term,1),reform(catch,2));
982 if (!(osend=send)) send="";
983 if ((catch_any=(catch && !strcmp(catch,"@")))) catch=NULL;
984 if ((errout=(*send=='!'))) send++;
985 errout|=(maxretryn==-1);
986 if ((extend=(*send=='~'))) send++;
987 alarmtime=readtimen*(extend?EXT_READTIME:1);
988 buf[bufl]='\0'; /* for d8() below */
989 d8("devcmd(), alarmtime=%ld, errout=%d, extend=%d, catch_any=%d, osend=%p, bufl=%d, buf: %s\n",
990 alarmtime,errout,extend,catch_any,osend,bufl,reform(buf,0));
991 assert(!catch || !strchr(catch,'\r')); /* we are no longer supporting 'noconvcr'! */
992 assert(!term || !strchr(term ,'\r'));
996 if (errout) return(NULL);
1002 d1("Resetting bufl.\n");
1004 l=VARVPRINTF(buf,send,ap); bufl=l+(!!osend);
1006 if (bufl>=sizeof(buf)-1) error(_("!Command too big (%d>%d)"),bufl,sizeof(buf)-1);
1007 if (verbose>=2) error(_(".devcmd formatted send=%s%s"),reform(buf,0),(osend?"+\"\\r\"":""));
1008 if (osend) buf[l]='\r';
1009 for (offs=0,got=0;offs<bufl;offs++) {
1011 usleep((offs?chartimen:cmdtimen)*1000);
1012 if (!offs && tcflush(devfd,TCIOFLUSH))
1013 error(_("^Error flushing I/O queue of device"));
1014 if (write(devfd,buf+offs,1)!=1) break;
1017 error(_("^Error forcing output of char at pos %d of cmd %s"),offs,reform(buf,0));
1021 error(_("^Wrote only %d of %d bytes of command"),got,bufl);
1026 if (!(terml=strlen(term))) {
1027 assert(!catch); assert(!catch_any);
1031 catchl=strlen(catch);
1032 fragl=MAX(terml,catchl);
1035 fragl=MAX(fragl,MAX(strlen(ERROR_SUBSTR1),strlen(ERROR_SUBSTR2)));
1036 record=recordend=NULL;
1041 /* "bufl" important */
1047 got=read(devfd,buf+bufl,sizeof(buf)-1-bufl);
1048 if (got==-1 && errno==EAGAIN) {
1051 got=read(devfd,buf+bufl,1);
1054 buf[bufl]='\0'; /* for strspn() below */
1055 if (!strcmp(term,"\n") && catch /* written to trap on 'devcmd("\n","+CMT:"," ")' */
1056 && bufl==strspn(buf,"\n" /* accept */)) { /* only newlines found */
1058 error(_(".Blank (%d newlines) input read, ignoring it"),bufl);
1059 bufl=0; /* discard newlines */
1060 return(&devcmd_empty_return);
1062 if (wasalarm) error(_("Maximum response timeout (%lds) exceeded"),alarmtime);
1063 else error(_("^Couldn't read device data (ret=%d)"),got);
1069 while (buf+bufl2>s && (s=memchr(s,'\0',buf+bufl2-s))) *s++=REPL_NULLCHAR;
1071 error(_("\nGot chunk of data from device: %s"),reform(buf+bufl,0));
1074 while (buf+bufl2>s && (s=memchr(s,'\r',buf+bufl2-s))) *s++='\n';
1078 catched(buf+bufl,edata); assert(!record || record==buf+bufl);
1079 assert(bufl<sizeof(buf)-1);
1081 assert(strlen(buf)==bufl);
1082 /* d3(">%s|%s<\n",buf,term); */
1083 if (strstr(buf,ERROR_SUBSTR1) || strstr(buf,ERROR_SUBSTR2)) {
1084 error(_("Found ERROR response on command %s"),reform(send,0));
1087 /* "record" may get NULLed here after successful 'catch'
1088 * but "recordend" will never be NULLed
1090 if (catch && !recordend && bufl>=catchl && (hit=strstr(buf,catch))) {
1092 catched(buf+bufl,edata); assert(!record || record==buf+bufl);
1094 if (catch_any && !recordend && buf[discard=strspn(buf,"\n" /* accept */)]) {
1096 catched(buf+bufl,edata); assert(!record || record==buf+bufl);
1098 if (((!catch && !catch_any) || catchdatal) && bufl>= terml
1099 && (hit=strstr((recordend?recordend:buf),term))) {
1100 memmove(buf,hit+terml,(bufl2=(buf+bufl)-(hit+terml))); bufl=bufl2;
1103 if (bufl<fragl) continue;
1104 memmove(buf,buf+bufl-(fragl-1),(bufl2=fragl-1));
1105 if (record ) record-=bufl-bufl2;
1106 if (recordend) recordend-=bufl-bufl2;
1111 assert(!catch && !catch_any);
1114 assert(!!catch || catch_any);
1116 catched(record+1,edata);
1117 if (verbose>=2) error(_(".Returning data %s for cmd %s"),reform(catchdata,0),reform(send,1));
1121 static int prepaddr(unsigned char *d,const char *addr)
1127 if ((plus=(*addr=='+'))) addr++;
1128 *++d=(plus?ADDR_INT:ADDR_NAT);
1130 if (*addr<'0' || *addr>'9')
1131 error(_("!Error during conversion of number at: %s"),addr);
1134 if ((flip=!flip)) *++d=0xF0|n;
1135 else *d=(*d&0x0F)|(n<<4U);
1140 static char *finalsmsc;
1141 #define SMSCBINSIZE (1+1+(MAXNUMLEN+1)/2)
1142 static char pdusmsc[SMSCBINSIZE*2+1];
1144 static inline char tohex(unsigned char x)
1147 if (x<10) return(x +'0');
1151 static inline void textconv(char *d,unsigned char *s,size_t len)
1161 static inline void smscset(void)
1163 char *s,*t,*e,*serr;
1164 unsigned char bin[2+(MAXNUMLEN+1)/2];
1166 if (smsc) devcmd(NULL,NULL,"\r\nAT+CSCA=\"%s\"",smsc);
1167 s=devcmd(NULL,"\n+CSCA:","\r\nAT+CSCA?");
1168 while (isspace(*s)) s++;
1169 if (!*s || !strcmp(s,"EMPTY"))
1170 error(_("!No SMSC set in mobile station found, please use option \"-s\""));
1171 if (verbose>=1) error(_("\nFound default SMSC in mobile: %s"),s);
1172 if (*s++!='"') error(_("!No left-quote found in: %s"),s);
1173 if (!(t=strrchr(s,'"'))) error(_("!No right-quote found in: %s"),s);
1175 error(_("!No SMS set in mobile station found, please use option \"-s\""));
1177 while (isspace(*t)) t++;
1181 if (*t++!=',') error(_("!No comma found after quotes in: %s"),s);
1182 while (isspace(*t)) t++;
1183 l=strtol(t,&serr,10);
1184 if ((l!=ADDR_NAT && l!=ADDR_INT) || (serr && *serr))
1185 error(_("!Type parse error in: %s"),s);
1186 if (l==ADDR_INT && *s!='+') *--s='+';
1189 if (verbose>=2) error(_("\nDecoded SMSC address: %s"),s);
1190 if (!NEED_PDUSMSC()) return;
1191 chk(finalsmsc=strdup(s));
1192 bin[0]=1+(prepaddr(bin,finalsmsc)+1)/2;
1193 textconv(pdusmsc,bin,bin[0]+1);
1196 static inline unsigned char charconv_send(char c,size_t offs)
1199 case '@': return(0);
1200 case '$': return(2);
1206 if ((c>='A' && c<='Z') || (c>='a' && c<='z') || (c>='0' && c<='9')) return(c);
1207 error(_("Can't convert character '%c' (0x%02X) at offs %d (0-based), substituted '?'"),
1208 c,(unsigned char)c,offs);
1213 static inline unsigned char charconv_recv(char c,size_t offs)
1214 { /* FIXME: unify with charconv_send() */
1216 case 0: return('@');
1217 case 2: return('$');
1221 /* strict checking not done, see charconv_send */
1224 /* Logo format shamelessly stolen from GNokii-0.3.0: http://www.gnokii.org/
1225 * Beware - Nokia Smart Messaging specification 1.0.0 and 2.0.0 is incompatible
1226 * with Nokia current product line implementation
1227 * http://www.forum.nokia.com/developers/smartmsg/download/ssm2_0_0.pdf
1230 static char *pdudata;
1231 static struct hexdata {
1232 struct hexdata *next;
1234 } *hexdata,**hexdatatail=&hexdata;
1236 static void nokiaprep(unsigned char *bin,size_t w)
1240 chk(hd=malloc(sizeof(*hd)));
1243 hexdatatail=&hd->next;
1244 textconv(hd->data,bin,w);
1245 if (verbose>=2) error(_("\nWill send hexdata: %s"),hd->data);
1248 static inline void logoread(void)
1251 char buf[32+140*8+1];
1252 unsigned char bin[140]={
1253 0x06, /* UDH length */
1256 0x15, 0x83, /* dest port (group gfx) */
1257 0x15, 0x83 /* src port (unused) */
1259 size_t got,r=0 /* GCC happiness */,w;
1262 int sizex,sizey,bit;
1264 #define WORD(n) (((unsigned char)buf[(n)])|(((unsigned char)buf[(n)+1])<<8))
1266 if (!(f=fopen(logoname,"rb")))
1267 error(_("^!Cannot open logo file \"%s\" for r/o"),logoname);
1268 got=fread(buf,1,sizeof(buf),f);
1269 chkfclose(f,logoname);
1270 if (got>=20 && !memcmp(buf,"NOL",4)) {
1271 VARPRINTF2(gsmnetf,"%03.3u%02.2u",WORD(6),WORD(8));
1272 assert(strlen(gsmnetf)==5);
1274 if (verbose>=1) error(_(".Reading NOL file \"%s\", GSMnet \"%s\", word@4=%d.."),
1275 logoname,gsmnetf,WORD(4));
1277 else if (got>=16 && !memcmp(buf,"NGG",4)) {
1279 if (verbose>=1) error(_(".Reading NGG file \"%s\", word@4=%d.."),
1282 else error(_("!Unknown file format of logo file \"%s\""),logoname);
1283 if (gsmnet && !strtrycasecmp(gsmnet,WORD_NET)) {
1284 if (!*gsmnetf) error(_("!NOL network code detection requested but NOL file not loaded, please specify network code"));
1287 if (!gsmnet || !strtrycasecmp(gsmnet,WORD_GROUP) || !*gsmnet) {
1288 error(_("\nSending logo as: group graphics"));
1292 error(_("\nSending logo as: operator logo for \"%s\""),gsmnet);
1293 bin[4]=0x82; /* dest port 0x1582 */
1296 sizex=WORD(r); sizey=WORD(r+2);
1297 if (verbose>=2) error(_(".Magic words: @+4=%d, @+6=%d, @+8=%d"),
1298 WORD(r+4),WORD(r+6),WORD(r+8));
1300 if (sizex<1 || sizex>255
1301 || sizey<1 || sizey>255) error(_("!Invalid size: %dx%d"),sizex,sizey);
1302 chars=((bits=sizex*sizey)+7)/8;
1303 if (r+bits>got) error(_("!Logo file \"%s\" too short - actual=%d, need(%dx%d)=%d"),
1304 logoname,got,sizex,sizey,r+chars);
1305 else if (r+bits<got)
1306 if (verbose>=1) error(_("Ignoring trailing garbage in \"%s\", used only %d bytes"),logoname,r+bits);
1307 if ((got=(7+(gsmnet?3:0)+4+chars))>140)
1308 error(_("!SMS size would be %d bytes but 140 is maximum"),got);
1311 bin[w++]=((gsmnet[1]&0x0F)<<4)|(gsmnet[0]&0x0F);
1312 bin[w++]=0xF0 |(gsmnet[2]&0x0F);
1313 bin[w++]=((gsmnet[4]&0x0F)<<4)|(gsmnet[3]&0x0F);
1315 bin[w++]=0x00; /* RFU by Nokia */
1316 bin[w++]=sizex; bin[w++]=sizey;
1317 bin[w++]=0x01; /* one B/W plane */
1320 for (bit=0x80;(bits>0) && (bit>0);bits--,bit>>=1) {
1321 if (buf[r]!='0' && buf[r]!='1')
1322 error(_("!Invalid character (neither '0' nor '1') in logo file \"%s\" at offset 0x%X"),
1324 if (buf[r++]=='1') bin[w]|=bit;
1328 assert(chars==-1); assert(bits==0); assert(w==got);
1333 static inline void ringread(void)
1336 unsigned char bin1[140]={
1340 0x15, 0x81, /* dest port (ring tones) */
1341 0x15, 0x81 /* src port (unused) */
1342 #define BIN1_PAYLOAD (140-7)
1344 unsigned char binn[140]={
1345 11, /* UDH length */
1348 0x15, 0x81, /* dest port (ring tones) */
1349 0x15, 0x81, /* src port (unused) */
1350 0x00, 0x03, /* multipart */
1351 /* 0x??, unique serial ID */
1352 /* 0x??, total messages */
1353 /* 0x??, message number (# from 1) */
1354 #define BINN_PAYLOAD (140-12)
1360 #define WORD(n) (((unsigned char)buf[(n)])|(((unsigned char)buf[(n)+1])<<8))
1362 if (!(f=fopen(ringname,"rb")))
1363 error(_("^!Cannot open ring file \"%s\" for r/o"),ringname);
1364 if ((size=getfilesize(f,ringname))==-1)
1365 error(_("!File size determination is essential to continue operation"));
1367 error(_("!File \"%s\" size %ld too small (must >=0x103)! Is it .000 file?"),
1369 if (fseek(f,0x100,SEEK_SET))
1370 error(_("^Seeking error on \"%s\", ignoring"),ringname);
1372 if (size<=BIN1_PAYLOAD) {
1373 if ((got=fread(bin1+7,1,size,f))!=size)
1374 error(_("^Read error on \"%s\", wanted %ld, got %d"),ringname,size,got);
1375 error(_("\nSending ring tone \"%s\" as single SMS (size %ld, max %d)"),
1376 ringname,size,BIN1_PAYLOAD);
1377 nokiaprep(bin1,7+size);
1380 totn=(size+BINN_PAYLOAD-1)/BINN_PAYLOAD;
1382 error(_("!File size %ld too large even for multi-SMS ring upload (max=%d)"),
1383 size,BINN_PAYLOAD*0xFF);
1386 error(_("\nSending ring tone \"%s\" as %d multi-SMSes (size %ld, max %d, frag %d)"),
1387 ringname,totn,size,BIN1_PAYLOAD,BINN_PAYLOAD);
1388 binn[9]=time(NULL)&0x100; /* rand() would be better but it is a compatibility pain */
1390 error(_("\nUsing unique multi-SMS ID 0x%02X"),(unsigned)binn[9]);
1391 for (fragn=1;fragn<=totn;fragn++) {
1393 want=MIN(size,BINN_PAYLOAD);
1394 if ((got=fread(binn+12,1,want,f))!=want)
1395 error(_("^Read error on \"%s\", wanted %d, got %d"),ringname,want,got);
1396 nokiaprep(binn,12+want);
1400 chkfclose(f,ringname);
1404 #define PICTURE_WIDTH (72)
1405 #define PICTURE_HEIGHT (28)
1407 static inline void pictureread(void)
1410 unsigned char bin1[140]={
1414 0x15, 0x8A, /* dest port (ring tones) */
1415 0x15, 0x8A /* src port (unused) */
1416 #define BIN1_PAYLOAD (140-7)
1418 unsigned char binn[140]={
1419 11, /* UDH length */
1422 0x15, 0x8A, /* dest port (ring tones) */
1423 0x15, 0x8A, /* src port (unused) */
1424 0x00, 0x03, /* multipart */
1425 /* 0x??, unique serial ID */
1426 /* 0x??, total messages */
1427 /* 0x??, message number (# from 1) */
1428 #define BINN_PAYLOAD (140-12)
1430 unsigned char header[]={
1431 0x30, /* version string '0' */
1432 0x02, /* item=OTA bitmap */
1433 #define PICTURE_BYTES ((PICTURE_WIDTH*PICTURE_HEIGHT+7)/8)
1434 #define PICTURE_BYTES_INCL_HEADER (PICTURE_BYTES +4/*header*/)
1435 PICTURE_BYTES_INCL_HEADER>>8,PICTURE_BYTES_INCL_HEADER&0xFF, /* picture size in bytes incl. header */
1436 0x00, /* animation pictures - 0=static picture */
1437 PICTURE_WIDTH,PICTURE_HEIGHT, /* picture size in pixels */
1438 0x01, /* picture depth - B/W */
1444 #define WORD(n) (((unsigned char)buf[(n)])|(((unsigned char)buf[(n)+1])<<8))
1446 if (!(f=fopen(picturename,"rb")))
1447 error(_("^!Cannot open picture file \"%s\" for r/o"),picturename);
1448 if ((size=getfilesize(f,picturename))==-1)
1449 error(_("!File size determination is essential to continue operation"));
1450 if (size!=PICTURE_BYTES)
1451 error(_("!File \"%s\" size %ld doesn't match .res size for %dx%d picture"),
1452 picturename,size,PICTURE_WIDTH,PICTURE_HEIGHT);
1453 if (size<=BIN1_PAYLOAD-sizeof(header)) {
1454 memcpy(bin1+7,header,sizeof(header));
1455 if ((got=fread(bin1+7+sizeof(header),1,size,f))!=size)
1456 error(_("^Read error on \"%s\", wanted %ld, got %d"),picturename,size,got);
1457 error(_("\nSending picture \"%s\" as single SMS (size %ld, max %d)"),
1458 picturename,size,BIN1_PAYLOAD-sizeof(header));
1459 nokiaprep(bin1,7+sizeof(header)+size);
1462 memcpy(binn+12,header,sizeof(header));
1463 totn=(sizeof(header)+size+BINN_PAYLOAD-1)/BINN_PAYLOAD;
1465 error(_("!File size %ld too large even for multi-SMS picture upload (max=%d)"),
1466 size,BINN_PAYLOAD*0xFF-sizeof(header));
1469 error(_("\nSending picture \"%s\" as %d multi-SMSes (size %ld, max %d, frag %d, header %d)"),
1470 picturename,totn,size,BIN1_PAYLOAD,BINN_PAYLOAD,sizeof(header));
1471 binn[9]=time(NULL)&0x100; /* rand() would be better but it is a compatibility pain */
1473 error(_("\nUsing unique multi-SMS ID 0x%02X"),(unsigned)binn[9]);
1474 for (fragn=1;fragn<=totn;fragn++) {
1475 size_t isheader=(fragn==1 ? sizeof(header) : 0);
1478 want=MIN(size,BINN_PAYLOAD-isheader);
1479 if ((got=fread(binn+12+isheader,1,want,f))!=want)
1480 error(_("^Read error on \"%s\", wanted %d, got %d"),picturename,want,got);
1481 nokiaprep(binn,12+isheader+want);
1485 chkfclose(f,picturename);
1489 static inline void genpdu(void)
1491 static unsigned char pdu[64+MAXNUMLEN/2+(MAXBODYLEN*7)/8];
1492 unsigned char *d=pdu;
1494 char inb=0,outb=0,xb,*bodyr;
1495 unsigned char inreg=0 /* GCC happiness */;
1500 i=prepaddr(d,phone);
1501 *d=i; d+=1+1+(i+1)/2;
1505 if (bodylen>MAXBODYLEN) {
1506 error(_("Body too large (%d>%d), cut"),bodylen,MAXBODYLEN);
1507 body[(bodylen=MAXBODYLEN)]='\0';
1511 assert(d<pdu+sizeof(pdu));
1512 while (bodylen || inb) {
1514 assert(bodylen>0); assert(!!*body);
1515 inreg=charconv_send(*bodyr++,offs++);
1525 d4("inb=%d,outb=%d,xb=%d\n",inb,outb,xb);
1527 *d|=((inreg>>(unsigned)(7-inb))&((1<<xb)-1))<<(unsigned)(8-outb);
1531 assert(d<pdu+sizeof(pdu));
1532 pdudata=malloc(2*(d-pdu)+1);
1533 textconv(pdudata,pdu,d-pdu);
1536 static inline void preparebody(void)
1538 FILE *fin=NULL /* GCC happiness */;
1541 if (body && readbody) {
1553 error(_("\nPlease enter the SMS text body, end with EOF (ctrl-D):"));
1556 if (!(fin=fopen(finame,"rt")))
1557 error(_("^!Can't open data file \"%s\" for r/o"),finame);
1559 chk(body=malloc(BODYLOAD));
1560 bodylen=fread(body,1,BODYLOAD,fin);
1562 error(_("^!Error reading stream \"%s\""),(finame?finame:_("<stdin>")));
1564 chkfclose(fin,finame);
1569 static int datawait(char immed)
1574 #else /* HAVE_POLL */
1576 #endif /* HAVE_POLL */
1580 if (!immed && verbose>=2)
1581 error(_(".Waiting for device incoming data.."));
1587 i=poll(&ufd,1,(immed?0:-1));
1588 #else /* HAVE_POLL */
1589 #ifdef HAVE_FD_SETSIZE
1590 if (devfd>=FD_SETSIZE)
1591 error(_("!Device file descriptor %d can't fit in select() FD_SETSIZE (%d)"),
1593 #endif /* HAVE_FD_SETSIZE */
1594 FD_ZERO(&rfds); FD_SET(devfd,&rfds);
1595 FD_ZERO(&xfds); FD_SET(devfd,&xfds);
1597 i=select(devfd+1,&rfds,NULL,&xfds,NULL);
1598 #endif /* HAVE_POLL */
1599 if (immed && i==0) return(0);
1600 if (i==-1 && errno==EINTR)
1601 goto retry; /* silent retry, for example SIGCHLD could occur */
1603 error(_("^Failed (retval %d) while waiting for data, ignoring"),i);
1606 if (ufd.revents&(POLLERR|POLLHUP))
1607 #else /* HAVE_POLL */
1608 if (FD_ISSET(devfd,&xfds))
1609 #endif /* HAVE_POLL */
1610 error(_("^Error while waiting for data, ignoring"));
1613 if (!(ufd.revents&POLLIN))
1614 #else /* HAVE_POLL */
1615 if (!(FD_ISSET(devfd,&rfds)))
1616 #endif /* HAVE_POLL */
1618 error(_("^No data input after waited for data, retrying"));
1624 static char *check_format(const char *fmt,const char *string)
1626 static char err[LINE_MAX],sub[50];
1628 const char *sf,*ss,*subp;
1630 for (sf=fmt,ss=string;(cf=*sf) && (cs=*ss);sf++,ss++) {
1636 if (isdigit(cs)) break;
1640 if (cs=='+' || cs=='-') break;
1645 VARPRINTF(sub,"'%c'",cf); subp=sub;
1647 if (!subp) continue;
1648 VARPRINTF5(err,_("Expected %s, found '%c' at pos %d of string [%s], formatstring [%s]"),
1649 subp,cs,ss-string,string,fmt);
1653 VARPRINTF2(err,_("String too short for format, string [%s], formatstring [%s]"),
1658 VARPRINTF2(err,_("Trailing garbage in string [%s], formatstring [%s]"),
1665 static char *receive_number,*receive_smsc;
1666 static time_t receive_time;
1669 static const struct {
1675 #define TP_ENT(a,b,c,d,e) { a,offsetof(struct tm,b),c,d,e }
1676 TP_ENT( 3,tm_year,0,99,N_("year")),
1677 TP_ENT( 6,tm_mon ,1,12,N_("month")),
1678 TP_ENT( 9,tm_mday,1,31,N_("day of month")),
1679 TP_ENT(12,tm_hour,0,23,N_("hour")),
1680 TP_ENT(15,tm_min ,0,59,N_("minute")),
1681 TP_ENT(18,tm_sec ,0,59,N_("second")),
1682 /* Time zone ignored */
1684 #define GETTIME(i) (*(int *)(((char *)&tm)+timeparse[(i)].tmpos))
1686 static void maketime(const char *string)
1691 for (i=0;i<NELEM(timeparse);i++) {
1693 if (val<timeparse[i].min || val>timeparse[i].max) {
1694 error(_("Weird value of %s, is %d but expected %d..%d, setting to %d"),
1695 _(timeparse[i].name),val,timeparse[i].min,timeparse[i].max,timeparse[i].min);
1696 GETTIME(i)=timeparse[i].min;
1699 if (tm.tm_year<70) tm.tm_year+=100;
1701 d7("mktime(y%dm%dd%dh%dm%ds%d)\n",
1702 tm.tm_year,tm.tm_mon,tm.tm_mday,tm.tm_hour,tm.tm_min,tm.tm_sec);
1703 tm.tm_isdst=-1; /* "timezone" info not available */
1704 if ((receive_time=mktime(&tm))==-1)
1705 error(_("^mktime(3) failed for %s"),string);
1708 /* +CMT: "+420602431329",,"99/10/25,03:21:03-00" */
1709 static int receive_headerparse(char *buf)
1714 #define DIGIT2ASC(s) (((s)[0]-'0')*10+((s)[1]-'0'))
1716 for (s=buf;*s==' ';s++);
1718 error(_("Cannot find initial '\"' in CMT header: %s"),buf);
1721 for (s1=s;*s && *s!='"';s++);
1723 error(_("Only one '\"' found in CMT header: %s"),buf);
1726 free(receive_smsc); receive_smsc=NULL;
1727 free(receive_number);
1728 chk(receive_number=malloc(s-s1+1));
1729 memcpy(receive_number,s1,s-s1); receive_number[s-s1]='\0';
1731 if ((err=check_phone(receive_number)) ||
1732 (err=check_format(",,\"99/99/99,99:99:99+99\"",s))) {
1733 error(_("%s in CMT header: %s"),err,buf);
1736 memset(&tm,0,sizeof(tm)); /* may be redundant */
1737 for (i=0;i<NELEM(timeparse);i++)
1738 GETTIME(i)=DIGIT2ASC(s+timeparse[i].strpos);
1744 static void signal_chld(int signo)
1749 signal(SIGCHLD,(RETSIGTYPE (*)(int))signal_chld);
1750 /* we don't care about siginterrupt(3) as it doesn't matter how it is set */
1752 d2("signal_chld: signo=%d\n",signo);
1753 while (0<(pid=waitpid(-1 /* ANY process */,&status,WNOHANG /* options */))) {
1755 error(_(".Child process w/PID %d has exited, %s, status=%d"),
1756 pid,(WIFEXITED(status)? _("normally") : _("abnormally")),(WIFEXITED(status) ? WEXITSTATUS(status) : -1));
1760 static void receive_text(char *bodyline)
1762 char *buf,*s,*s1,*s2,*s3;
1768 d2("receive_text: %s\n",bodyline);
1769 signal(SIGCHLD,(RETSIGTYPE (*)(int))signal_chld);
1777 error(_(".Spawned child receive-SMS process w/PID %d"),pid);
1778 return; /* parent context */
1781 error(_("Can't fork(2), process spawning may block receive"));
1783 else { /* child process */
1789 s1=strchr(s1+(s1!=s),'%');
1790 } while (s1 && s1[1]!='p' && s1[1]!='T' && s1[1]!='t' && s1[1]!='s');
1792 pushargstack_one(s,0);
1796 pushargstack_one(s,0);
1801 pushargstack_one(receive_number,0);
1804 VARPRINTF(tbuf,"%ld",receive_time);
1805 pushargstack_one(tbuf,0);
1808 if (receive_time==-1) break;
1809 if (!(s2=ctime(&receive_time))) {
1810 error(_("Failing ctime(3), ignoring substitution"));
1813 if ((s3=strchr(s2,'\n'))) *s3='\0';
1814 pushargstack_one(s2,0);
1817 if (receive_smsc) pushargstack_one(receive_smsc,0);
1822 buf=glueargstack(NULL,NULL); assert(buf);
1823 if (!(f=popen(buf,"w"))) {
1824 error(_("^Failing spawn of receive command: %s"),buf);
1827 if (fputs(bodyline,f)<0 || putc('\n',f)!='\n')
1828 error(_("^Failing write to child receive command: %s"),buf);
1830 error(_("^Spawned receive command failure (code %d): %s"),i,buf);
1833 if (pid==-1) return;
1834 exit(EXIT_SUCCESS); /* cleanup() has been disabled */
1837 static inline unsigned char fromhex(unsigned c)
1840 return(c<'A'?c-('0'&0xDF):(c-('A'&0xDF))+0xA);
1843 static int teldecode(char *text,unsigned char *bin,size_t digits)
1848 for (i=0;i<digits;text++,i++) {
1863 static void sctsparse(unsigned char *bin,const char *pduline,int offs)
1865 #define DIGIT2BIN(v) (((v)&0x0F)*10+(((v)>>4)&0x0F))
1869 memset(&tm,0,sizeof(tm)); /* may be redundant */
1870 for (i=0;i<NELEM(timeparse);offs++,i++) {
1871 if ((*bin&0x0F)>0x09 || (*bin&0xF0)>0x90) {
1872 error(_("Invalid value of \"%s\" at offset %d in: %s"),
1873 timeparse[i].name,offs,pduline);
1876 GETTIME(i)=DIGIT2BIN(*bin);
1884 static void receive_pdu(char *pduline)
1886 unsigned char pdu[140+0x100],*pdup,*pdue,oalen,inreg;
1887 char text[160+1],*textp,*s,*pdulinescan;
1888 size_t pdulinel=strlen(pduline),want;
1892 d2("receive_pdu: %s\n",pduline);
1893 if (pdulinel>2*sizeof(pdu))
1894 { error(_("PDU too long (%d/2) to be valid: %s"),pdulinel,pduline); return; }
1896 { error(_("PDU length odd (%d): %s"),pdulinel,pduline); return; }
1898 { error(_("PDU length %d too small (min. 2*%d): %s"),pdulinel,13,pduline); return; }
1899 for (pdup=pdu,pdulinescan=pduline;*pdulinescan;pdulinescan+=2) {
1900 if (!isxdigit(pdulinescan[0]) || !(isxdigit(pdulinescan[1])))
1901 { error(_("Invalid hex byte: %c%c on byte %d in: %s"),
1902 pdulinescan[0],pdulinescan[1],pdup-pdu,pduline); return; }
1903 *pdup++=(fromhex(pdulinescan[0])<<4)|fromhex(pdulinescan[1]);
1912 { error(_("SMSC length too large (%d, max. %d): %s"),*pdu,10,pduline); return; }
1913 chk(receive_smsc=malloc(1+2*(*pdu)+1));
1915 if (pdu[1]==ADDR_INT) *s++='+';
1917 if (pdu[1]!=ADDR_NAT)
1918 error(_("Unknown address type 0x%02X of %s, ignoring in PDU: %s"),pdu[1],_("SMSC"),pduline); return;
1920 if (teldecode(s,pdu+2,2*(*pdu-1)-((pdu[1+(*pdu)]&0xF0)==0xF0)))
1921 error(_("Some digits unrecognized in %s \"%s\", ignoring in PDU: %s"),_("SMSC"),receive_smsc,pduline);
1924 if (*pdup&0x03) /* PDU type */
1925 error(_("Unrecognized PDU type 0x%02X at offset %d, dropping: %s"),*pdup,pdup-pdu,pduline);
1927 free(receive_number);
1928 if ((oalen=*pdup++)>2*0x10) /* OA len */
1929 { error(_("Originating number too large (0x%X, max. 2*0x%X): %s"),oalen,0x10,pduline); return; }
1930 if (pdup+(want=1+(oalen+1)/2+10)>pdue)
1931 { error(_("PDU length too short (want %d, is %d): %s"),(pdup-pdu)+want,pdue-pdu,pduline); return; }
1932 chk(receive_number=malloc(1+2*(*pdup)+1));
1934 if (*pdup==ADDR_INT) *s++='+';
1936 if (*pdup!=ADDR_NAT)
1937 error(_("Unknown address type 0x%02X of %s, ignoring in PDU: %s"),*pdup,_("originating number"),pduline); return;
1940 if (teldecode(s,pdup,oalen))
1941 error(_("Some digits unrecognized in %s \"%s\", ignoring in PDU at offset %d: %s"),
1942 _("originating number"),receive_number,pdup-pdu,pduline);
1944 if (*pdup) /* PID */
1945 error(_("PID number %02X unsupported, ignoring: %s"),*pdup,pduline);
1947 if (*pdup) { /* DCS */
1948 if ((*pdup&0xF4)==0xF4)
1949 { error(_("DCS 0x%02X indicates 8-bit data, unsupported, dropping: %s"),*pdup,pduline); return; }
1950 error(_("DCS 0x%02X unsupported, will attempt decoding: %s"),*pdup,pduline);
1953 sctsparse(pdup,pduline,pdup-pdu);
1957 if (pdue-pdup>140) {
1958 error(_("PDU data (%d) exceed maximum length of %d bytes, cut: %s"),
1959 pdue-pdup,140,pduline);
1963 if (pdup+udlb>pdue) {
1968 error(_("PDU data length (%d/7->%d/8) longer than data (%d), cut to %d/7->%d/8: %s"),
1969 udl,udlb,pdue-pdup,udl1,udlb1,pduline);
1970 udl=udl1; udlb=udlb1;
1973 assert(pdup+udlb==pdue); /* should be checked by 'PDU length too short' above */
1976 inreg=0; /* GCC happiness */
1983 assert(textp<text+160);
1989 d4("inb=%d,outb=%d,xb=%d\n",inb,outb,xb);
1991 *textp|=((inreg>>(unsigned)(8-inb))&((1<<xb)-1))<<(unsigned)(7-outb);
1994 *textp=charconv_recv(*textp,textp-text);
2006 const char *const msg;
2008 { &maxretry,&maxretryn,"maxretry" },
2009 { &readtime,&readtimen,"readtime" },
2010 { &chartime,&chartimen,"chartime" },
2011 { &cmdtime ,&cmdtimen ,"cmdtime" },
2012 { &baud ,&baudn ,"baud" },
2015 int main(int argc,char **argv)
2018 int i,cmgf=-1 /* GCC happiness */;
2020 speed_t portbaud=0 /* GCC happiness */;
2021 enum modenum argsmode;
2024 if ((s=strrchr((pname=*argv),'/'))) pname=s+1;
2027 /* Initialize the i18n stuff */
2028 bindtextdomain(PACKAGE,LOCALEDIR);
2029 if (!setlocale(LC_ALL,""))
2030 error("Locale not supported by C library");
2031 textdomain(PACKAGE);
2037 error(_("atexit(3) not available at compilation time, device cleanup may be missed"));
2039 signal(SIGTERM,(RETSIGTYPE (*)(int))cleanup);
2040 signal(SIGQUIT,(RETSIGTYPE (*)(int))cleanup);
2041 signal(SIGINT ,(RETSIGTYPE (*)(int))cleanup);
2042 signal(SIGHUP ,(RETSIGTYPE (*)(int))cleanup);
2043 assert(mode==MODE_UNKNOWN);
2044 for (i=0;i<NELEM(longopts);i++) {
2045 if (longopts[i].val<MODE_FIRST) break;
2046 if (!strstr(pname,longopts[i].name)) continue;
2047 if (mode==MODE_UNKNOWN || mode==longopts[i].val) {
2048 mode=longopts[i].val;
2055 processargs(argc,argv,_("<command-line>"));
2056 if ((s=getenv("HOME"))) {
2058 char *buf=malloc(l+50);
2061 strcpy(buf+l,CONFIG_HOME);
2065 readfile(CONFIG_MAIN,1);
2068 error(_(".Detected mode \"%s\" from my program name \"%s\""),MODE_NAME(argsmode),pname);
2070 error(_(".Automatic mode detection unsuccessul for my progam name \"%s\""),pname);
2074 error(_("!Operation mode unset, use --send or similiar command, see help (-h)"));
2075 error(_(".Running program in mode \"%s\""),MODE_NAME(mode));
2078 case MODE_SEND: /* FALLTHRU */
2079 case MODE_SEND_MOBILDOCK: cmdline_send (); break;
2080 case MODE_LOGO_SEND: cmdline_logo_send (); break;
2081 case MODE_RING_SEND: cmdline_ring_send (); break;
2082 case MODE_PICTURE_SEND: cmdline_picture_send(); break;
2083 case MODE_RECEIVE: cmdline_receive (); break;
2087 for (i=0;i<NELEM(nullcheck);i++) {
2088 const struct nullcheck *n=nullcheck+i;
2090 if (*n->var) continue;
2091 if (n->reqd && !(MODE_BIT(mode)&n->reqd)) continue;
2092 error(_("Missing parameter \"%s\""),_(n->name));
2095 if (fatal) error(_("!Previous %s considered unrecoverable"),(fatal==1?_("error"):_("errors")));
2097 if (!logname) logname=DEF_LOGNAME;
2098 if (!lockfile) lockfile=DEF_LOCKFILE;
2099 if (!device) device=DEF_DEVICE;
2101 for (i=0;i<NELEM(numarg);i++) {
2103 if (!*numarg[i].sp) continue;
2104 *numarg[i].ip=strtol(*numarg[i].sp,&serr,0);
2105 if (*numarg[i].ip<0 || *numarg[i].ip>=LONG_MAX || !serr || *serr)
2106 error(_("!Number parse error for parameter \"%s\" of \"%s\" at: %s"),
2107 numarg[i].msg,*numarg[i].sp,serr);
2110 readtimen=(mode==MODE_SEND_MOBILDOCK?DEF_READTIME_MOBILDOCK:DEF_READTIME);
2111 if (mode==MODE_SEND_MOBILDOCK) mode=MODE_SEND;
2113 if (!strchr(device,'/')) {
2114 size_t l=strlen(device);
2115 chk(s=malloc(5+l+1));
2121 devicename=strrchr(device,'/')+1; assert(!!(devicename-1));
2122 for (i=0,s=lockfile;*s;s++) {
2123 if (*s!='%') continue;
2125 if (*s=='%') continue;
2127 if (i) error(_("!Only one \"%%s\" permitted in lockfile format-string"));
2130 error(_("!Invalid format-character '%c' in lockfile format-string, only \"%%s\" allowed"),*s);
2134 if (!(logf=fopen(logname,"a")))
2135 error(_("^!Error opening log \"%s\" for append"),logname);
2136 logmsg(_("Starting up: %s"),PACKAGE " " VERSION);
2145 case MODE_LOGO_SEND:
2148 case MODE_RING_SEND:
2151 case MODE_PICTURE_SEND:
2154 case MODE_RECEIVE: break;
2158 error(_("Warning: -f / --file is forbidden with mode \"%s\""),MODE_NAME(mode));
2160 if (!strcmp(smsmode,"pdu" ) || !strcmp(smsmode,"0"))
2161 force_smsmode=FSM_PDU ;
2162 else if (!strcmp(smsmode,"text") || !strcmp(smsmode,"1"))
2163 force_smsmode=FSM_TEXT;
2165 error(_("!Unrecognized %s argument \"%s\", supported only: %s"),"-M/--smsmode",smsmode,"pdu/0/text/1");
2168 if (!strcmp(pdusmscmode,"count-in"))
2169 force_pdusmscmode=FPSM_COUNT_IN;
2170 else if (!strcmp(pdusmscmode,"count-out"))
2171 force_pdusmscmode=FPSM_COUNT_OUT;
2172 else if (!strcmp(pdusmscmode,"none"))
2173 force_pdusmscmode=FPSM_NONE;
2175 error(_("!Unrecognized %s argument \"%s\", supported only: %s"),"-P/--pdusmscmode",pdusmscmode,"count-in/count-out/none");
2176 try_pdusmscmode=force_pdusmscmode;
2180 case 2400: portbaud= B2400; break;
2181 case 4800: portbaud= B4800; break;
2182 case 9600: portbaud= B9600; break;
2183 case 19200: portbaud=B19200; break;
2184 case 38400: portbaud=B38400; break;
2185 case 57600: portbaud=B57600; break;
2187 error(_("!Specified baudrate %ld is not supported"),baudn);
2189 if (verbose>=2) error(_(".Will use baudrate %ld with hexval 0x%X"),baudn,portbaud);
2191 if (lockfile && *lockfile && VARPRINTF(lockreal,lockfile,devicename)>0) {
2193 if (verbose>=1) error(_(".Locking device \"%s\" by \"%s\".."),device,lockreal);
2197 if ((end-=start)>LOCKREPORT)
2198 logmsg(_("Device lock succeeded after %ld seconds"),(long)end);
2203 if (verbose>=1) error(_(".Opening device \"%s\".."),device);
2204 if ((devfd=open(device,O_RDWR|O_NDELAY))<0)
2205 error(_("^!Cannot open device \"%s\" for r/w access"),device);
2209 if (tcgetattr(devfd,&restios))
2210 error(_("^Unable to get termios settings"));
2212 restios.c_cflag=(restios.c_cflag&~(CBAUD|CBAUDEX))|B0|HUPCL;
2215 tios.c_iflag=IGNBRK|IGNPAR|(handshake_rtscts ? 0 : IXON|IXOFF);
2217 tios.c_cflag=CS8|CREAD|CLOCAL|HUPCL|portbaud|(handshake_rtscts ? CRTSCTS : 0);
2218 tios.c_lflag=IEXTEN|NOFLSH;
2219 memset(tios.c_cc,_POSIX_VDISABLE,sizeof(tios.c_cc));
2222 cfsetispeed(&tios,portbaud);
2223 if (cfsetospeed(&tios,portbaud)|cfsetispeed(&tios,portbaud))
2224 error(_("^Error setting termios baudrate on device"));
2225 if (tcflush(devfd,TCIOFLUSH))
2226 error(_("^Error flushing termios (TCIOFLUSH) on device"));
2227 if (tcsetattr(devfd,TCSANOW,&tios))
2228 error(_("^!Unable to set initial termios device settings"));
2232 devcmd("",NULL,"\r\nAT\033\032"); /* ESCAPE, CTRL-Z */
2233 devcmd(NULL,NULL,"\r\nAT");
2235 if (mode==MODE_SEND || mode==MODE_RECEIVE) {
2238 /* condition is _negative_ here: */
2239 if (force_smsmode==FSM_TEXT || !devcmd(NULL,NULL,"!\r\nAT+CMGF=0")) {
2240 if (force_smsmode==FSM_PDU || !devcmd(NULL,NULL,"!\r\nAT+CMGF=1"))
2241 { retrying(); continue; }
2244 error(_(".Using AT+CMGF=1 (text mode).."));
2250 error(_(".Using AT+CMGF=0 (PDU mode).."));
2258 devcmd("\n> ",NULL,"\r\nAT+CMGS=\"%s\"",phone);
2259 s=devcmd(NULL,"\n+CMGS:","!~%s\032",body);
2262 devcmd("\n> ",NULL,"\r\nAT+CMGS=%d",(
2263 (try_pdusmscmode==FPSM_COUNT_IN ? strlen(pdusmsc) : 0)
2264 +strlen(pdudata))/2);
2265 s=devcmd(NULL,"\n+CMGS:","!~%s%s\032",
2266 (try_pdusmscmode!=FPSM_NONE ? pdusmsc : ""),
2268 if (!s && force_pdusmscmode==FPSM_AUTO) {
2269 if (FPSM_MAX==try_pdusmscmode++)
2270 try_pdusmscmode=FPSM_MIN;
2276 case MODE_LOGO_SEND:
2277 case MODE_RING_SEND:
2278 case MODE_PICTURE_SEND: {
2281 restore="\r\nAT+CSMP=17,,0,0";
2282 devcmd(NULL,NULL,"\r\nAT+CSMP=81,,0,245");
2283 while ((hd=hexdata)) {
2284 devcmd("\n> ",NULL,"\r\nAT+CMGS=\"%s\"",phone);
2285 if (!(s=devcmd(NULL,"\n+CMGS:","!~%s\032",hd->data))) break;
2286 if ((hexdata=hd->next)) pushargstack_one(s,0);
2292 restore="\r\nAT+CNMI=,0";
2293 devcmd(NULL,NULL,"\r\nAT+CNMI=,2");
2294 devcmd(NULL,NULL,"\r\nAT+CSDH=0");
2298 /* Never bail-out when we got up to this point */
2299 if (maxretryn!=-1 && verbose>=1)
2300 error(_(".Initialization successful, infinite retry count set"));
2303 receive_headerparse(" \"+420602123456\",,\"99/10/25,03:21:03-00\"");
2304 receive_accept("TESTBODY");
2308 if (!lockdevice(1)) {
2310 error(_(".Dialout detected, waiting for lock.."));
2311 if (verbose>=1) error(_(".Closing device \"%s\".."),device);
2313 error(_("Error closing device \"%s\""),device);
2317 d1("Lock-device succeeded\n");
2319 d1("Reading a message for us...\n");
2320 if (!(s=devcmd("\n","+CMT:"," ")))
2322 if (s==&devcmd_empty_return) /* only newlines found */
2323 goto continue_receive;
2324 if (cmgf && !(i=receive_headerparse(s)))
2325 error(_("Receive-header parsing failed on: %s"),s);
2326 if (!(s=devcmd("\n","@"," ")))
2329 if (i) receive_text(s);
2331 else receive_pdu(s);
2332 } while (datawait(1));
2333 } /* return to 'continue receive' point */
2337 if (!s) { retrying(); goto retryall; }
2339 pushargstack_one(s,0); s=NULL;
2340 if (verbose>=1) while ((s=nextargstack())) {
2341 while (isspace(*s)) s++;
2342 error(_("\nMessage successfuly sent with MR (Message Reference): %s"),s);
2344 devcmd(NULL,NULL,"\r\nAT");
2347 logmsg(_("SMS sent (after %d retries), %d part(s)"),retrycnt,parts);
2349 logmsg(_("SMS sent (after %d retries)"),retrycnt);
2350 return(EXIT_SUCCESS);