Fixed formatstring parameters (only error messages involved).
[mdsms.git] / mdsms.c
1 #include "config.h"
2 #ifndef lint
3 static char rcsid[] ATTR_UNUSED = "$Id$";
4 #endif
5
6 #include "setup.h"
7
8 #ifdef HAVE_STDIO_H
9 #include <stdio.h>
10 #endif
11 #ifdef HAVE_STDLIB_H
12 #include <stdlib.h>
13 #endif
14 #ifdef HAVE_STRING_H
15 #include <string.h>
16 #endif
17 #ifdef HAVE_SIGNAL_H
18 #include <signal.h>
19 #endif
20 #ifdef HAVE_STDARG_H
21 #include <stdarg.h>
22 #endif
23 #ifdef HAVE_LIMITS_H
24 #include <limits.h>
25 #endif
26 #ifdef HAVE_CTYPE_H
27 #include <ctype.h>
28 #endif
29 #ifdef HAVE_TERMIOS_H
30 #include <termios.h>
31 #endif
32 #ifdef HAVE_UNISTD_H
33 #include <unistd.h>
34 #endif
35 #ifdef HAVE_ASSERT_H
36 #include <assert.h>
37 #endif
38 #ifdef HAVE_SYS_TYPES_H
39 #include <sys/types.h>
40 #endif
41 #ifdef HAVE_SYS_STAT_H
42 #include <sys/stat.h>
43 #endif
44 #ifdef HAVE_FCNTL_H
45 #include <fcntl.h>
46 #endif
47 #ifdef HAVE_ERRNO_H
48 #include <errno.h>
49 #endif
50 #ifdef HAVE_TIME_H
51 #include <time.h>
52 #endif
53 #ifdef HAVE_SYS_TIME_H
54 #include <sys/time.h>
55 #endif
56 #ifdef HAVE_SYS_POLL_H
57 #include <sys/poll.h>
58 #endif
59 #ifdef HAVE_LOCALE_H
60 #include <locale.h>
61 #endif
62
63 #ifdef HAVE_GETOPT_LONG
64 #include <getopt.h>
65 #else
66 #include "getopt.h"
67 #endif
68
69 #define NELEM(x) (sizeof((x))/sizeof(*(x)))
70
71 #ifndef DEBUG
72 #define dbg(cmd)
73 #else
74 #define dbg(cmd) cmd
75 #endif
76 /* ANSI C does not allow macro with variable arguments */
77 #define dO stderr
78 #define dB(a) dbg(fprintf a)
79
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))
88
89 static const char version[]="Mobile Device SMS tool (" PACKAGE " " VERSION ")\n";
90
91 static int verbose
92 #ifdef DEBUG
93         =0xFFFF
94 #endif
95         ;
96 static char *pname;
97 static int dis_cleanup=0,devfd=-1;
98
99 static char *phone,*device,*logname,*lockfile,*smsc,*maxretry,*readtime,*chartime,*cmdtime,*baud,*restore;
100 static int readbody;
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 */
104 static char *body;
105 /* --logo-send specific */
106 static char *logoname,*gsmnet;
107 /* --ring-send specific */
108 static char *ringname;
109
110 static enum modenum {
111   MODE_UNKNOWN=0,
112 /* must differ from regular char-s */
113   MODE_FIRST         =0x3400,
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 */
119         } mode=MODE_UNKNOWN;
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)))
123
124 static unsigned mode_stamp;
125
126 /* pdusmsc variable has to be filled in */
127 #define NEED_PDUSMSC() (mode==MODE_SEND)
128
129 static char *devicename; /* path stripped */
130 static char lockreal[512],locked;
131
132 static struct termios restios,tios;
133 static char restios_yes;
134 static FILE *logf;
135
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)
138 {
139 time_t stamp;
140 char *ctm,*s;
141 pid_t mypid=-1;
142 char host[LINE_MAX];
143
144         if (!logf) return;
145         if (mypid==-1) {
146                 mypid=getpid();
147                 if (gethostname(host,sizeof(host))) strcpy(host,_("<ERROR>"));
148                 }
149         time(&stamp);
150         ctm=ctime(&stamp);
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);
156         fputc('\n',logf);
157         fflush(logf);
158 }
159
160 static void logmsg(const char *fmt,...) ATTR_PRINTFORMAT(1,2);
161 static void logmsg(const char *fmt,...)
162 {
163 va_list ap;
164         va_start(ap,fmt);
165         vlogmsg(0,'\n',fmt,ap);
166         va_end(ap);
167 }
168
169 static void error(const char *fmt,...) ATTR_PRINTFORMAT(1,2);
170 static void error(const char *fmt,...)
171 {
172 va_list ap;
173 char fatal,pm;
174
175         if ((pm=(*fmt=='^'))) fmt++;
176         fatal=*fmt;
177         if (fatal=='!' || fatal=='.' || fatal=='\n') fmt++;
178         else fatal=0;
179
180         fprintf(stderr,"%s: ",pname);
181         va_start(ap,fmt);
182         vfprintf(stderr,fmt,ap);
183         if (fatal=='!') vlogmsg(pm,fatal,fmt,ap);
184         va_end(ap);
185         if (pm) { fputs(": ",stderr); fputs(strerror(errno),stderr); }
186         if (fatal!='\n') fputc((fatal=='.'?'.':'!'),stderr);
187         fputc('\n',stderr);
188         if (fatal=='!') exit(EXIT_FAILURE);
189 }
190
191 static void chk(const void *p)
192 {
193         if (p) return;
194         error(_("!Virtual memory exhausted"));
195 }
196
197 static char *devcmd(const char *term,const char *catch,const char *send,...) ATTR_PRINTFORMAT(3,4);
198
199 static void unlockdevice(int hard)
200 {
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);
207         locked=0;
208 }
209
210 static void cleanup(void)
211 {
212         d1("cleanup()\n");
213         if (dis_cleanup) return;
214         if (restore) {
215 char *cmd=restore;
216                 restore=NULL;
217                 devcmd(NULL,NULL,"\r\nAT");
218                 devcmd(NULL,NULL,cmd);
219                 devcmd(NULL,NULL,"\r\nAT");
220                 }
221         if (restios_yes) {
222                 if (tcsetattr(devfd,TCSANOW,&restios))
223                         error(_("^Error restoring termios for device"));
224                 restios_yes=0;
225                 }
226         unlockdevice(1);
227         dis_cleanup=1;
228         exit(EXIT_FAILURE);
229 }
230
231 static void usage(void)
232 {
233         fprintf(stderr,_("\
234 \n\
235 %s\
236 \n\
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\
245   --receive:\n\
246              <command name>\n\
247   --logo-send:\n\
248              <dest. phone> <logo filename> [<GSMnet id>]\n\
249   --ring-send:\n\
250              <dest. phone> <ring filename>\n\
251 \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\
258 \t\t(def. \"%s\")\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\
269 \n\
270 --send / --send-mobildock:\n\
271  -f, --file\tRead contents of message from file instead\n\
272 --receive:\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\
280 --logo-send:\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\
284 \n\
285 You may need to use the following line to catch all of this help text:\n\
286 ./mdsms 2>&1|more\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);
290         exit(EXIT_FAILURE);
291 }
292
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},
306 {"config"  ,1,0,'c'},
307 {"device"  ,1,0,'d'},
308 {"log"     ,1,0,'L'},
309 {"baud"    ,1,0,'b'},
310 {"lockfile",1,0,'l'},
311 {"smsc"    ,1,0,'s'},
312 {"maxretry",1,0,'m'},
313 {"readtime",1,0,'r'},
314 {"chartime",1,0,'t'},
315 {"cmdtime" ,1,0,'T'},
316 {"file"    ,0,0,'f'},
317 {"verbose" ,0,0,'v'},
318 {"help"    ,0,0,'h'},
319 {"version" ,0,0,'V'},
320 {NULL      ,0,0,0  }};
321
322 static void processargs(int argp,char **args,const char *from);
323
324 static char *cfgstack[MAXCFGLOOP];
325 static unsigned cfgstacki=0;
326
327 static void chkfclose(FILE *f,const char *fname)
328 {
329         if (fclose(f))
330                 error(_("^Error closing \"%s\""),fname);
331 }
332
333 static long getfilesize(FILE *f,const char *fname)
334 {
335 long size;
336
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);
341         rewind(f);
342         return(size);
343 }
344
345 static void readfile(const char *fname,char quiet)
346 {
347 FILE *f;
348 size_t got;
349 char *args[MAXCFGARGS],*d,*s,blank,quote;
350 unsigned argp;
351 char *buf;
352 long size;
353 static unsigned tot=0;
354
355         if (tot++>=MAXCFGNUM) {
356                 if (tot==MAXCFGNUM+1) error(_("Too many config files to read, max is %d, break-out"),MAXCFGNUM);
357                 return;
358                 }
359         if (!(f=fopen(fname,"rt"))) {
360                 if (!quiet) error(_("^Can't open config file \"%s\" for r/o"),fname);
361                 return;
362                 }
363                 
364         if (verbose>=2) error(_(".Reading config file \"%s\""),fname);
365         if ((size=getfilesize(f,fname))==-1) size=0;
366         if (size>MAXCONFIG) 
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);
372         chkfclose(f,fname);
373         buf[got]='\0';
374         args[0]=pname;
375         for (argp=1,d=s=buf,blank=1,quote=0;s<buf+got;s++) {
376 char c=*s;
377
378                 if (!quote && isspace(c)) {
379                         if (!blank) {
380                                 *d='\0';
381                                 blank=1;
382                                 if (verbose>=2) error(_("\nConfig \"%s\": arg#%d: %s"),fname,argp-1,args[argp-1]);
383                                 }
384                         continue;
385                         }
386                 if (blank) {
387                         if (argp>=NELEM(args)-1) {
388                                 error(_("Too many arguments in \"%s\", from offset %d ignored"),fname,s-buf);
389                                 break;
390                                 }
391                         args[argp++]=s;
392                         d=s;
393                         blank=0;
394                         }
395                 if (c=='\\') { *d++=*++s; continue; }
396                 if (c=='"' || c=='\'') {
397                         if (!quote   ) { quote=c; continue; }
398                         if ( quote==c) { quote=0; continue; }
399                         /* FALLTHRU */
400                         }
401                 *d++=c;
402                 }
403         args[argp]=NULL;
404         processargs(argp,args,fname);
405         free(buf);
406 }
407
408 static struct argstack {
409         struct argstack *next;
410         int num,offset;
411         const char *from;
412         char *arg[1];
413         } *argstack;
414
415 static struct argstack **argstack_tail=&argstack;
416 static size_t lastargstack_len;
417 static const char *lastargstack_from;
418 static int lastargstack_index;
419
420 static size_t argstack_size;
421 static int argstack_num;
422
423 static void pushargstack(char **args,int num,int offset,const char *from,char stack)
424 {
425 struct argstack *as;
426 int i;
427
428         if (!num) return;
429         assert(num>=1);
430         chk(as=malloc(sizeof(*as)+sizeof(as->arg)*(num-1)));
431         as->num=num;
432         as->offset=offset;
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]);
438                 }
439         argstack_num+=num;
440         if (stack) {
441                 as->next=argstack;
442                 argstack=as;
443                 }
444         else {
445                 as->next=NULL;
446                 *argstack_tail=as;
447                 argstack_tail=&as->next;
448                 }
449 }
450
451 static void pushargstack_one(char *s,char stack)
452 { pushargstack(&s,1,0,NULL,stack); }
453
454 static char *nextargstack(void)
455 {
456 static int order=0;
457 char *r;
458
459         if (argstack && order==argstack->num) {
460 struct argstack *as=argstack;
461                 if (!(argstack=as->next))
462                         argstack_tail=&argstack;
463                 order=0;
464                 free((char *)as->from);
465                 lastargstack_from=NULL;
466                 free(as);
467                 }
468         if (!argstack) {
469                 assert(!argstack_num); assert(!argstack_size);
470                 return(NULL);
471                 }
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;
479         return(r);
480 }
481
482 static char *glueargstack(size_t *destlenp,const char *glue)
483 {
484 size_t gluel=(glue?strlen(glue):0),destlen;
485 char *dest,*d,*s;
486
487         if (!argstack_num) {
488                 chk(dest=strdup(""));
489                 if (destlenp) *destlenp=0;
490                 return(dest);
491                 }
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);
497                 free(s);
498                 d+=lastargstack_len;
499                 if (!argstack_num) break;
500                 if (!glue) continue;
501                 memcpy(d,glue,gluel);
502                 d+=gluel;
503                 assert(d<=dest+destlen);
504                 }
505         assert(!argstack_num);
506         assert(d==dest+destlen);
507         *d='\0';
508         return(dest);
509 }
510
511 static struct {
512         const char c;
513         char **const var;
514         unsigned stamp;
515         } optset[]={
516                 { 'd',&device   },
517                 { 'L',&logname  },
518                 { 'b',&baud     },
519                 { 'l',&lockfile },
520                 { 's',&smsc     },
521                 { 'm',&maxretry },
522                 { 'r',&readtime },
523                 { 't',&chartime },
524                 { 'T',&cmdtime  },
525         };
526
527 static void processargs(int argp,char **args,const char *from)
528 {
529 int optc;
530 static unsigned seq=0;
531 int i;
532
533         seq++;
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) {
536                 case 'c':
537                         if (cfgstacki>=NELEM(cfgstack)) {
538                                 error(_("Looping (%d) during attempt to read config file \"%s\", break-out"),NELEM(cfgstack),from);
539                                 break;
540                                 }
541                         chk(cfgstack[cfgstacki++]=strdup(optarg));
542                         break;
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);
548                                                 break;
549                                                 }
550                                         free(*optset[i].var);
551                                         chk(*optset[i].var=strdup(optarg));
552                                         optset[i].stamp=seq;
553                                         break;
554                                         }
555                         assert(i<NELEM(optset));
556                         break;
557                 case MODE_SEND:
558                 case MODE_SEND_MOBILDOCK:
559                 case MODE_RECEIVE:
560                 case MODE_LOGO_SEND:
561                 case MODE_RING_SEND:
562                         if (mode_stamp && mode_stamp!=seq) break;
563                         mode=optc;
564                         mode_stamp=seq;
565                         break;
566                 case 'f':
567                         readbody++;
568                         break;
569                 case 'v':
570                         verbose++;
571                         break;
572                 case 'V':
573                         fprintf(stderr,version);
574                         exit(EXIT_FAILURE);
575                 default:
576                         if (optc!='h')
577                                 error(_("\nLast getopt(3) error occured during parsing option %d from \"%s\"! Follows help:"),optind-1,from);
578                         usage();
579                         break;
580                 }
581         pushargstack(args+optind,argp-optind,optind,from,1);
582         while (cfgstacki) {
583 char *s=cfgstack[--cfgstacki];
584
585                 assert(cfgstacki>=0);
586                 readfile(s,0);
587                 free(s);
588                 assert(cfgstacki>=0 && cfgstacki<NELEM(cfgstack));
589                 }
590 }
591
592 static const struct nullcheck {
593         char **var;
594         enum modenum reqd;
595         const char *name;
596         } 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 */
602 #if 0
603                 {&gsmnet,MODE_BIT(MODE_LOGO_SEND),N_("GSM operator network code")},
604                 {&device,0,N_("device for communication")},
605 #endif
606         };
607 static char **emptycheck[]={&logname,&smsc,&logoname,&gsmnet};
608
609 static inline void emptyclean(void)
610 {
611 int i;
612
613         for (i=0;i<NELEM(emptycheck);i++)
614                 if (*emptycheck[i] && !**emptycheck[i]) {
615                         free(*emptycheck[i]);
616                              *emptycheck[i]=NULL;
617                         }
618 }
619
620 static inline void cmdline_done(void)
621 {
622 char *s;
623         while ((s=nextargstack())) {
624                 error(_("\nExcessive option %d from \"%s\" ignored: %s"),
625                         lastargstack_index,lastargstack_from,s);
626                 free(s);
627                 }
628         emptyclean();
629 }
630
631 static char *check_phone(const char *phone)
632 {
633 const char *s,*s1;
634 static char err[LINE_MAX];
635
636         for (s=s1=(phone+(*phone=='+'));*s && s-s1<MAXNUMLEN;s++)
637                 if (!isdigit(*s)) {
638                         VARPRINTF2(err,_("Invalid digit '%c' in phone number - at offset %d"),
639                                 *s,s-phone);
640                         return(err);
641                         }
642         if (!*s) return(NULL);
643         VARPRINTF2(err,_("Phone number too long (%d), max. %d digits allowed"),
644                 strlen(s1),MAXNUMLEN);
645         return(err);
646 }
647
648 static void cmdline_phone(void)
649 {
650         if (!phone && (phone=nextargstack())) {
651 char *s;
652
653                 if ((s=check_phone(phone)))
654                         error(_("!%s in option %d from \"%s\": %s"),
655                                         s,lastargstack_index,lastargstack_from,phone);
656                 }
657 }
658
659 static inline void cmdline_receive(void)
660 {
661 char *s;
662
663         if (!body && argstack_num) {
664                 body=glueargstack(&bodylen," ");
665                 for (s=body;(s=strchr(s,'%'));s++)
666                         switch (*++s) {
667                                 case 'p': case 'T': case 't': case 's': break;
668                                 default:
669                                         error(_("Unknown formatsymbol '%c' (use \"%%%%%c\" to fix it) at pos %d in: %s"),
670                                                 *s,*s,s-body,body);
671                                 }
672                 }
673 }
674
675 static inline void cmdline_send(void)
676 {
677         cmdline_phone();
678         if (!body && argstack_num)
679                 body=glueargstack(&bodylen," ");
680 }
681
682 static inline void cmdline_logo_send(void)
683 {
684 char *ogsmnet;
685
686         cmdline_phone();
687         if (!logoname) logoname=nextargstack();
688         if (!gsmnet && (ogsmnet=nextargstack())) {
689 char *s,*d,e=0;
690
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);
698                                 e=1;
699                                 break;
700                                 }
701                         if ((d-gsmnet)!=5) {
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);
705                                 e=1;
706                                 }
707                         if (!e) *d='\0';
708                         else {
709                                 error(_("\nGSMnet option %d from \"%s\" rejected due to previous errors: %s"),
710                                         lastargstack_index,lastargstack_from,ogsmnet);
711                                 free(gsmnet);
712                                 gsmnet=NULL;
713                                 }
714                         }
715                 }
716 }
717
718 static inline void cmdline_ring_send(void)
719 {
720         cmdline_phone();
721         if (!ringname) ringname=nextargstack();
722 }
723
724 static void lockclose(int fd)
725 {
726         if (close(fd))
727                 error(_("Error closing lockfile \"%s\""),lockreal);
728 }
729
730 static inline int lockdevice(int attempt)
731 {
732 int fd=-1;
733 char buf[64];
734 ssize_t got;
735 int delay=0;
736 char empty=0;
737 pid_t pid;
738
739         d2("lockdevice(), locked=%d\n",locked);
740         if (locked) return (++locked);
741         for (;;) {
742                 if (fd!=-1) lockclose(fd);
743 recheck:
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) {
749 isempty:
750                         if (empty>=DEVLOCK_MAXEMPTY) {
751                                 error(_(".Lockfile \"%s\" is still not valid, removing it"),lockreal);
752                                 goto remove;
753                                 }
754                         empty++;
755                         continue;
756                         }
757                 assert(got<sizeof(buf));
758                 buf[got]='\0';
759                 if (sscanf(buf,"%d",&pid)!=1) goto isempty;
760                 empty=0;
761                 errno=0;
762                 if (kill(pid,0) && errno!=ESRCH && errno!=EPERM)
763                         error(_("^Error during checking consciousness of PID %d"),pid);
764                 if (errno!=ESRCH) {
765                         if (attempt) return(0);
766                         continue;
767                         }
768                 error(_(".Lockfile \"%s\" is stale (PID %d), removing it"),lockreal,pid);
769 remove:
770                 lockclose(fd);
771                 if (unlink(lockreal))
772                         error(_("^Error removing foreign lockfile \"%s\""),lockreal);
773                 break;
774                 }
775         errno=0;
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);
779                 }
780         locked=1;
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);
784         lockclose(fd);
785         return((locked=1));
786 }
787
788 static char wasalarm=0;
789 static void sigalarm(int signo);
790
791 static void setalarm(void)
792 {
793         signal(SIGALRM,(RETSIGTYPE (*)(int))sigalarm);
794 #ifdef HAVE_SIGINTERRUPT
795         siginterrupt(SIGALRM,1);
796 #endif
797 }
798
799 static void sigalarm(int signo)
800 {
801         setalarm();
802         wasalarm=1;
803         if (verbose>=1) error(_("Timed out"));
804 }
805
806 static void blocking(char yes)
807 {
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")));
812         state=yes;
813 }
814
815 static const char *record;
816 static char *catchdata;
817 static size_t catchdatal,catchdatasiz;
818
819 static void catched(const char *end,char edata)
820 {
821 size_t len;
822 const char *p;
823
824         if (!record) return;
825         assert(end>=record);
826         p=memchr(record,edata,end-record);
827         if ((len=(p?p:end)-record)) {
828                 if (!catchdata)
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);
834                 catchdatal+=len;
835                 }
836         record=(p?NULL:end);
837         assert(catchdatal<=catchdatasiz);
838 }
839
840 static int retrycnt=0;
841 static void retrying(void)
842 {
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);
845 }
846
847 static char *reform(const char *s,int slot)
848 {
849 static struct formslot {
850         char *s;
851         size_t l;
852         } arr[3];
853 char c,*d;
854 struct formslot *fs;
855
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));
860         d=fs->s;
861         for (*d++='"';(c=*s);s++) {
862                 if (d>=fs->s+fs->l-10) {
863 off_t o=d-fs->s;
864                         chk(fs->s=realloc(fs->s,(fs->l=(fs->l?fs->l*2:LINE_MAX))));
865                         d=fs->s+o;
866                         }
867                 if (c!='\\' && c!='"' && isprint(c)) { *d++=c; continue; }
868                 *d++='\\';
869                 switch (c) {
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;
875                         default:
876                                 d+=sprintf(d,"x%02X",(unsigned char)c);
877                                 break;
878                         }
879                 }
880         *d++='"'; *d='\0';
881         return(fs->s);
882 }
883
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,...)
886 {
887 size_t l,bufl2,terml,catchl=0 /* GCC happiness */,fragl,offs;
888 static char buf[LINE_MAX];
889 static size_t bufl;
890 ssize_t got;
891 char *hit,*s;
892 va_list ap;
893 char errout,extend,noconvcr,edata;
894 long alarmtime;
895 const char *osend;
896 static const char emptystring[]="";
897
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));
908         if (0) {
909 err:
910                 alarm(0);
911                 if (errout) return(NULL);
912                 retrying();
913                 }
914         catchdatal=0;
915         if (osend) {
916                 bufl=0;
917                 d1("Resetting bufl.\n");
918                 va_start(ap,send);
919                 l=VARVPRINTF(buf,send,ap); bufl=l+(!!osend);
920                 va_end(ap);
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++) {
926                         alarm(MAXSENDTIME);
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;
931                         got++;
932                         if (tcdrain(devfd))
933                                 error(_("^Error forcing output of char at pos %d of cmd %s"),offs,reform(buf,0));
934                         }
935                 alarm(0);
936                 if (got!=bufl) {
937                         error(_("^Wrote only %d of %d bytes of command"),got,bufl);
938                         goto err;
939                         }
940                 }
941
942         if (!(terml=strlen(term))) {
943                 assert(!catch);
944                 return(NULL);
945                 }
946         if (catch) {
947                 catchl=strlen(catch);
948                 fragl=MAX(terml,catchl);
949                 }
950         else fragl=terml;
951         fragl=MAX(fragl,MAX(strlen(ERROR_SUBSTR1),strlen(ERROR_SUBSTR2)));
952         record=NULL;
953         wasalarm=0;
954         alarm(alarmtime);
955         edata=(noconvcr?'\r':'\n');
956         if (!osend) {
957                 got=bufl;
958                 bufl=0;
959                 goto skipread;
960                 }
961         for (;;) {
962                 blocking(0);
963                 errno=0;
964                 got=read(devfd,buf+bufl,sizeof(buf)-1-bufl);
965                 if (got==-1 && errno==EAGAIN) {
966                         blocking(1);
967                         errno=0;
968                         got=read(devfd,buf+bufl,1);
969                         }
970                 if (got<=0) {
971                         if (wasalarm) error(_("Maximum response timeout (%lds) exceeded"),alarmtime);
972                         else error(_("^Couldn't read device data (ret=%d)"),got);
973                         goto err;
974                         }
975 skipread:
976                 bufl2=bufl+got;
977                 buf[bufl2]='\0';
978                 s=buf+bufl;
979                 while (buf+bufl2>s && (s=memchr(s,'\0',buf+bufl2-s))) *s++=REPL_NULLCHAR;
980                 if (verbose>=3)
981                         error(_("\nGot chunk of data from device: %s"),reform(buf+bufl,0));
982                 if (!noconvcr) {
983                         s=buf+bufl;
984                         while (buf+bufl2>s && (s=memchr(s,'\r',buf+bufl2-s))) *s++='\n';
985                         }
986                 bufl=bufl2;
987                 catched(buf+bufl,edata); assert(!record || record==buf+bufl);
988                 assert(bufl<sizeof(buf)-1);
989                 buf[bufl]='\0';
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));
994                         goto err;
995                         }
996                 if (catch && !record && bufl>=catchl && (hit=strstr(buf,catch))) {
997                         record=hit+catchl;
998                         catched(buf+bufl,edata); assert(!record || record==buf+bufl);
999                         }
1000                 if (         bufl>= terml && (hit=strstr(buf,term))) {
1001                         memmove(buf,hit+terml,(bufl2=(buf+bufl)-(hit+terml))); bufl=bufl2;
1002                         break;
1003                         }
1004                 if (bufl<fragl) continue;
1005                 memmove(buf,buf+bufl-(fragl-1),(bufl2=fragl-1)); bufl=bufl2;
1006                 if (record) record=buf+fragl-1;
1007                 }
1008         alarm(0);
1009         if (!catchdatal) {
1010                 if (!catch) return("");
1011                 error(_("Data requested on command %s but no found after term %s"),reform(send,0),reform(term,1));
1012                 goto err;
1013                 }
1014         assert(!!catch);
1015         record=emptystring;
1016         catched(record+1,edata);
1017         if (verbose>=2) error(_(".Returning data %s for cmd %s"),reform(catchdata,0),reform(send,1));
1018         return(catchdata);
1019 }
1020
1021 static int prepaddr(unsigned char *d,const char *addr)
1022 {
1023 int tot=0;
1024 char flip=0,plus;
1025 unsigned char n;
1026
1027         if ((plus=(*addr=='+'))) addr++;
1028         *++d=(plus?ADDR_INT:ADDR_NAT);
1029         while (*addr) {
1030                 if (*addr<'0' || *addr>'9')
1031                         error(_("!Error during conversion of number at: %s"),addr);
1032                 tot++;
1033                 n=(*addr++)-'0';
1034                 if ((flip=!flip)) *++d=0xF0|n;
1035                 else *d=(*d&0x0F)|(n<<4U);
1036                 }
1037         return(tot);
1038 }
1039
1040 static char *finalsmsc;
1041 #define SMSCBINSIZE (1+1+(MAXNUMLEN+1)/2)
1042 static char pdusmsc[SMSCBINSIZE*2+1];
1043
1044 static inline char tohex(unsigned char x)
1045 {
1046         x&=0x0F;
1047         if (x<10) return(x   +'0');
1048                   return(x-10+'A');
1049 }
1050
1051 static inline void textconv(char *d,unsigned char *s,size_t len)
1052 {
1053         while (len--) {
1054                 *d++=tohex(*s>>4U);
1055                 *d++=tohex(*s    );
1056                 s++;
1057                 }
1058         *d='\0';
1059 }
1060
1061 static inline void smscset(void)
1062 {
1063 char *s,*t,*e,*serr;
1064 long l;
1065 unsigned char bin[2+(MAXNUMLEN+1)/2];
1066
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);
1075         if (s+1==t)
1076                 error(_("!No SMS set in mobile station found, please use option \"-s\""));
1077         e=t++;
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++;
1085         else *s='+';
1086         *e='\0';
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);
1092 }
1093
1094 static inline unsigned char charconv_send(char c,size_t offs)
1095 {
1096         switch (c) {
1097                 case '@': return(0);
1098                 case '$': return(2);
1099                 case 0: assert(0);
1100                 default:
1101                         return(c&0x7F);
1102                 }
1103 #if 0
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);
1107         return('?');
1108 #endif
1109 }
1110
1111 static inline unsigned char charconv_recv(char c,size_t offs)
1112 { /* FIXME: unify with charconv_send() */
1113         switch (c) {
1114                 case 0: return('@');
1115                 case 2: return('$');
1116                 default:
1117                         return(c);
1118                 }
1119 /* strict checking not done, see charconv_send */
1120 }
1121
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
1126  */
1127
1128 static char *pdudata;
1129 static struct hexdata {
1130         struct hexdata *next;
1131         char data[140*2+1];
1132         } *hexdata,**hexdatatail=&hexdata;
1133
1134 static void nokiaprep(unsigned char *bin,size_t w)
1135 {
1136 struct hexdata *hd;
1137         assert(w<=140);
1138         chk(hd=malloc(sizeof(*hd)));
1139         *hexdatatail=hd;
1140         hd->next=NULL;
1141         hexdatatail=&hd->next;
1142         textconv(hd->data,bin,w);
1143         if (verbose>=2) error(_("\nWill send hexdata: %s"),hd->data);
1144 }
1145
1146 static inline void logoread(void)
1147 {
1148 FILE *f;
1149 char buf[32+140*8+1];
1150 unsigned char bin[140]={
1151         0x06, /* UDH length */
1152         0x05, /* IEI */
1153         0x04, /* IEDL */
1154         0x15, 0x83, /* dest port (group gfx) */
1155         0x00, 0x00  /* src port (unused) */
1156         };
1157 size_t got,r=0 /* GCC happiness */,w;
1158 ssize_t chars,bits;
1159 char gsmnetf[10];
1160 int sizex,sizey,bit;
1161
1162 #define WORD(n) (((unsigned char)buf[(n)])|(((unsigned char)buf[(n)+1])<<8))
1163
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);
1171                 r=10;
1172                 if (verbose>=1) error(_(".Reading NOL file \"%s\", GSMnet \"%s\", word@4=%d.."),
1173                         logoname,gsmnetf,WORD(4));
1174                 }
1175         else if (got>=16 && !memcmp(buf,"NGG",4)) {
1176                 r=6;
1177                 if (verbose>=1) error(_(".Reading NGG file \"%s\", word@4=%d.."),
1178                         logoname,WORD(4));
1179                 }
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"));
1183                 gsmnet=gsmnetf;
1184                 }
1185         if (!gsmnet || !strtrycasecmp(gsmnet,WORD_GROUP) || !*gsmnet) {
1186                 error(_("\nSending logo as: group graphics"));
1187                 gsmnet=NULL;
1188                 }
1189         else {
1190                 error(_("\nSending logo as: operator logo for \"%s\""),gsmnet);
1191                 bin[4]=0x82; /* dest port 0x1582 */
1192                 }
1193         
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));
1197         r+=10;
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);
1207         w=7;
1208         if (gsmnet) {
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);
1212                 }
1213         bin[w++]=0x00; /* RFU by Nokia */
1214         bin[w++]=sizex; bin[w++]=sizey;
1215         bin[w++]=0x01; /* one B/W plane */
1216         while (chars--) {
1217                 bin[w]=0;
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"),
1221                                         logoname,r);
1222                         if (buf[r++]=='1') bin[w]|=bit;
1223                         }
1224                 w++;
1225                 }
1226         assert(chars==-1); assert(bits==0); assert(w==got);
1227         nokiaprep(bin,w);
1228 #undef WORD
1229 }
1230
1231 static inline void ringread(void)
1232 {
1233 FILE *f;
1234 unsigned char bin1[140]={
1235         6, /* UDH length */
1236         0x05, /* IEI */
1237         0x04, /* IEDL */
1238         0x15, 0x81, /* dest port (ring tones) */
1239         0x15, 0x81  /* src port (unused) */
1240 #define BIN1_PAYLOAD (140-7)
1241         };
1242 unsigned char binn[140]={
1243         11, /* UDH length */
1244         0x05, /* IEI */
1245         0x04, /* IEDL */
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)
1253         };
1254 size_t got,want;
1255 int totn,fragn;
1256 long size;
1257
1258 #define WORD(n) (((unsigned char)buf[(n)])|(((unsigned char)buf[(n)+1])<<8))
1259
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"));
1264         if (size<0x103)
1265                 error(_("!File \"%s\" size %ld too small (must >=0x103)! Is it .000 file?"),
1266                         ringname,size);
1267         if (fseek(f,0x100,SEEK_SET))
1268                 error(_("^Seeking error on \"%s\", ignoring"),ringname);
1269         size-=0x100;
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);
1276                 }
1277         else {
1278                 totn=(size+BINN_PAYLOAD-1)/BINN_PAYLOAD;
1279                 if (totn>0xFF)
1280                         error(_("!File size %ld too large even for multi-SMS ring upload (max=%d)"),
1281                                 size,BINN_PAYLOAD*0xFF);
1282                 binn[10]=totn;
1283                 if (verbose>=1)
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 */
1287                 if (verbose>=1)
1288                         error(_("\nUsing unique multi-SMS ID 0x%02X"),(unsigned)binn[9]);
1289                 for (fragn=1;fragn<=totn;fragn++) {
1290                         binn[11]=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);
1295                         size-=want;
1296                         }
1297                 }
1298         chkfclose(f,ringname);
1299 #undef WORD
1300 }
1301
1302 static inline void genpdu(void)
1303 {
1304 static unsigned char pdu[64+MAXNUMLEN/2+(MAXBODYLEN*7)/8];
1305 unsigned char *d=pdu;
1306 int i;
1307 char inb=0,outb=0,xb,*bodyr;
1308 unsigned char inreg=0 /* GCC happiness */;
1309 size_t offs=0;
1310
1311         *d++=PDU_TYPE;
1312         *d++=PDU_MR;
1313         i=prepaddr(d,phone);
1314         *d=i; d+=1+1+(i+1)/2;
1315         *d++=PDU_PID;
1316         *d++=PDU_DCS;
1317         *d++=PDU_VP;
1318         if (bodylen>MAXBODYLEN) {
1319                 error(_("Body too large (%d>%d), cut"),bodylen,MAXBODYLEN);
1320                 body[(bodylen=MAXBODYLEN)]='\0';
1321                 }
1322         bodyr=body;
1323         *d=bodylen;
1324         assert(d<pdu+sizeof(pdu));
1325         while (bodylen || inb) {
1326                 if (!inb) {
1327                         assert(bodylen>0); assert(!!*body);
1328                         inreg=charconv_send(*bodyr++,offs++);
1329                         bodylen--;
1330                         inb=7;
1331                         }
1332                 if (!outb) {
1333                         *++d=0x00;
1334                         outb=8;
1335                         }
1336                 xb=MIN(inb,outb);
1337 #if 0
1338                 d4("inb=%d,outb=%d,xb=%d\n",inb,outb,xb);
1339 #endif
1340                 *d|=((inreg>>(unsigned)(7-inb))&((1<<xb)-1))<<(unsigned)(8-outb);
1341                 inb-=xb; outb-=xb;
1342                 }
1343         d++;
1344         assert(d<pdu+sizeof(pdu));
1345         pdudata=malloc(2*(d-pdu)+1);
1346         textconv(pdudata,pdu,d-pdu);
1347 }
1348
1349 static inline void preparebody(void)
1350 {
1351 FILE *fin=NULL /* GCC happiness */;
1352 char *finame;
1353
1354         if (body && readbody) {
1355                 finame=body;
1356                 body=NULL;
1357                 }
1358         else {
1359                 finame=NULL;
1360                 fin=stdin;
1361                 }
1362         if (body) return;
1363         readbody=0;
1364         if (!finame) {
1365                 if (verbose>=1)
1366                         error(_("\nPlease enter the SMS text body, end with EOF (ctrl-D):"));
1367                 }
1368         else {
1369                 if (!(fin=fopen(finame,"rt")))
1370                         error(_("^!Can't open data file \"%s\" for r/o"),finame);
1371                 }
1372         chk(body=malloc(BODYLOAD));
1373         bodylen=fread(body,1,BODYLOAD,fin);
1374         if (bodylen==-1)
1375                 error(_("^!Error reading stream \"%s\""),(finame?finame:_("<stdin>")));
1376         if (finame) {
1377                 chkfclose(fin,finame);
1378                 free(finame);
1379                 }
1380 }
1381
1382 static int datawait(char immed)
1383 {
1384 int i;
1385 #ifdef HAVE_POLL
1386 struct pollfd ufd;
1387 #else /* HAVE_POLL */
1388 fd_set rfds,xfds;
1389 #endif /* HAVE_POLL */
1390
1391         assert(devfd>=0);
1392 retry:
1393         errno=0;
1394
1395 #ifdef HAVE_POLL
1396         ufd.fd=devfd;
1397         ufd.events=POLLIN;
1398         ufd.revents=0;
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)"),
1404                         devfd,FD_SETSIZE);
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);
1411         if (i!=1)
1412                 error(_("^Failed (retval %d) while waiting for data, ignoring"),i);
1413
1414 #ifdef HAVE_POLL
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"));
1420
1421 #ifdef HAVE_POLL
1422         if (!(ufd.revents&POLLIN))
1423 #else /* HAVE_POLL */
1424         if (!(FD_ISSET(devfd,&rfds)))
1425 #endif /* HAVE_POLL */
1426                 {
1427                 error(_("^No data input after waited for data, retrying"));
1428                 goto retry;
1429                 }
1430         return(1);
1431 }
1432
1433 static char *check_format(const char *fmt,const char *string)
1434 {
1435 static char err[LINE_MAX],sub[50];
1436 char *subp,cf,cs;
1437 const char *sf,*ss;
1438
1439         for (sf=fmt,ss=string;(cf=*sf) && (cs=*ss);sf++,ss++) {
1440                 subp=NULL;
1441                 switch (cf) {
1442                         case '?':
1443                                 break;
1444                         case '9':
1445                                 if (isdigit(cs)) break;
1446                                 subp=_("digit");
1447                                 break;
1448                         case '+':
1449                                 if (cs=='+' || cs=='-') break;
1450                                 subp=_("+/- sign");
1451                                 break;
1452                         default:
1453                                 if (cf==cs) break;
1454                                 VARPRINTF(sub,"'%c'",cf); subp=sub;
1455                         }
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);
1459                 return(err);
1460                 }
1461         if (*sf) {
1462                 VARPRINTF2(err,_("String too short for format, string [%s], formatstring [%s]"),
1463                         string,fmt);
1464                 return(err);
1465                 }
1466         if (*ss) {
1467                 VARPRINTF2(err,_("Trailing garbage in string [%s], formatstring [%s]"),
1468                         string,fmt);
1469                 return(err);
1470                 }
1471         return(NULL);
1472 }
1473
1474 static char *receive_number,*receive_smsc;
1475 static time_t receive_time;
1476
1477 struct tm tm;
1478 static const struct {
1479         off_t strpos;
1480         off_t tmpos;
1481         int min,max;
1482         const char *name;
1483         } timeparse[]={
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 */
1492                 };
1493 #define GETTIME(i) (*(int *)(((char *)&tm)+timeparse[(i)].tmpos))
1494
1495 static void maketime(const char *string)
1496 {
1497 int val;
1498 int i;
1499
1500         for (i=0;i<NELEM(timeparse);i++) {
1501                 val=GETTIME(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;
1506                         }
1507                 }
1508         if (tm.tm_year<70) tm.tm_year+=100;
1509         tm.tm_mon--;
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);
1514 }
1515
1516 /* +CMT: "+420602431329",,"99/10/25,03:21:03-00" */
1517 static int receive_headerparse(char *buf)
1518 {
1519 char *s,*s1,*err;
1520 int i;
1521
1522 #define DIGIT2ASC(s) (((s)[0]-'0')*10+((s)[1]-'0'))
1523
1524         for (s=buf;*s==' ';s++);
1525         if (*s++!='"') {
1526                 error(_("Cannot find initial '\"' in CMT header: %s"),buf);
1527                 return(0);
1528                 }
1529         for (s1=s;*s && *s!='"';s++);
1530         if (!*s) {
1531                 error(_("Only one '\"' found in CMT header: %s"),buf);
1532                 return(0);
1533                 }
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';
1538         s++;
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);
1542                 return(0);
1543                 }
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;
1548         tm.tm_mon--;
1549         maketime(s+2);
1550         return(1);
1551 #undef DIGIT2ASC
1552 }
1553
1554 static void receive_text(char *bodyline)
1555 {
1556 char *buf,*s,*s1,*s2,*s3;
1557 pid_t pid;
1558 char tbuf[32];
1559 int i;
1560 FILE *f;
1561
1562         d2("receive_text: %s\n",bodyline);
1563 #if RECEIVE_TEST
1564         pid=0;
1565 #else
1566         pid=fork();
1567 #endif
1568         if (pid>0) return; /* parent context */
1569         if (pid==-1) {
1570                 error(_("Can't fork(2), process spawning may block receive"));
1571                 }
1572         else { /* child process */
1573                 dis_cleanup=1;
1574                 }
1575         for (s=body;*s;) {
1576                 s1=s;
1577                 do {
1578                         s1=strchr(s1+(s1!=s),'%');
1579                         } while (s1 && s1[1]!='p' && s1[1]!='T' && s1[1]!='t' && s1[1]!='s');
1580                 if (!s1) {
1581                         pushargstack_one(s,0);
1582                         break;
1583                         }
1584                 *s1='\0';
1585                 pushargstack_one(s,0);
1586                 *s1++='%';
1587                 s=s1;
1588                 switch (*s++) {
1589                         case 'p':
1590                                 pushargstack_one(receive_number,0);
1591                                 break;
1592                         case 'T':
1593                                 VARPRINTF(tbuf,"%ld",receive_time);
1594                                 pushargstack_one(tbuf,0);
1595                                 break;
1596                         case 't':
1597                                 if (receive_time==-1) break;
1598                                 if (!(s2=ctime(&receive_time))) {
1599                                         error(_("Failing ctime(3), ignoring substitution"));
1600                                         break;
1601                                         }
1602                                 if ((s3=strchr(s2,'\n'))) *s3='\0';
1603                                 pushargstack_one(s2,0);
1604                                 break;
1605                         case 's':
1606                                 if (receive_smsc) pushargstack_one(receive_smsc,0);
1607                                 break;
1608                         default: assert(0);
1609                         }
1610                 }
1611         buf=glueargstack(NULL,NULL); assert(buf);
1612         if (!(f=popen(buf,"w"))) {
1613                 error(_("^Failing spawn of receive command: %s"),buf);
1614                 goto err;
1615                 }
1616         if (fputs(bodyline,f)<0 || putc('\n',f)!='\n')
1617                 error(_("^Failing write to child receive command: %s"),buf);
1618         if ((i=pclose(f)))
1619                 error(_("^Spawned receive command failure (code %d): %s"),i,buf);
1620 err:
1621         free(buf);
1622         if (pid==-1) return;
1623         exit(EXIT_SUCCESS); /* cleanup() has been disabled */
1624 }
1625
1626 static inline unsigned char fromhex(char c)
1627 {
1628         c&=0xDF;
1629         return(c<'A'?c-'0':(c-'A')+0xA);
1630 }
1631
1632 static int teldecode(char *text,unsigned char *bin,size_t digits)
1633 {
1634 unsigned char b;
1635 int r=0,i;
1636
1637         for (i=0;i<digits;text++,i++) {
1638                 if (!(i&1)) b=*bin;
1639                 else b=(*bin++)>>4;
1640                 b&=0x0F;
1641                 if (b<=0x09)
1642                         *text=b+'0';
1643                 else {
1644                         *text='?';
1645                         r++;
1646                         }
1647                 }
1648         *text='\0';
1649         return(r);
1650 }
1651
1652 static void sctsparse(unsigned char *bin,const char *pduline,int offs)
1653 {
1654 #define DIGIT2BIN(v) (((v)&0x0F)*10+(((v)>>4)&0x0F))
1655 int i;
1656
1657         receive_time=-1;
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);
1663                         return;
1664                         }
1665                 GETTIME(i)=DIGIT2BIN(*bin);
1666                 bin++;
1667                 }
1668         maketime(pduline);
1669
1670 #undef DIGIT2BIN
1671 }
1672
1673 static void receive_pdu(char *pduline)
1674 {
1675 unsigned char pdu[140+0x100],*pdup,*pdue,oalen,inreg;
1676 char text[160+1],*textp,*s;
1677 size_t pdulinel=strlen(pduline),want;
1678 size_t udl,udlb;
1679 int inb,outb,xb;
1680
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; }
1684         if (pdulinel&1)
1685                 { error(_("PDU length odd (%d): %s"),pdulinel,pduline); return; }
1686         if (pdulinel<2*13)
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]);
1693                 }
1694         pdue=pdup;
1695         free(receive_smsc);
1696         if (*pdu<=1) {
1697                 receive_smsc=NULL;
1698                 }
1699         else {
1700                 if (*pdu>10)
1701                         { error(_("SMSC length too large (%d, max. %d): %s"),*pdu,10,pduline); return; }
1702                 chk(receive_smsc=malloc(1+2*(*pdu)+1));
1703                 s=receive_smsc;
1704                 if (pdu[1]==ADDR_INT) *s++='+';
1705                 else {
1706                         if (pdu[1]!=ADDR_NAT)
1707                                 error(_("Unknown address type 0x%02X of %s, ignoring in PDU: %s"),pdu[1],_("SMSC"),pduline); return;
1708                         }
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);
1711                 }
1712         pdup=pdu+1+(*pdu);
1713         if (*pdup&0x03) /* PDU type */
1714                 error(_("Unrecognized PDU type 0x%02X at offset %d, dropping: %s"),*pdup,pdup-pdu,pduline);
1715         pdup++;
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));
1722         s=receive_number;
1723         if (*pdup==ADDR_INT) *s++='+';
1724         else {
1725                 if (*pdup!=ADDR_NAT)
1726                         error(_("Unknown address type 0x%02X of %s, ignoring in PDU: %s"),*pdup,_("originating number"),pduline); return;
1727                 }
1728         pdup++;
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);
1732         pdup+=(oalen+1)/2;
1733         if (*pdup) /* PID */
1734                 error(_("PID number %02X unsupported, ignoring: %s"),*pdup,pduline);
1735         pdup++;
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);
1740                 }
1741         pdup++;
1742         sctsparse(pdup,pduline,pdup-pdu);
1743         pdup+=7;
1744         /* UDL */
1745         udl=*pdup++;
1746         if (pdue-pdup>140) {
1747                 error(_("PDU data (%d) exceed maximum length of %d bytes, cut: %s"),
1748                         pdue-pdup,140,pduline);
1749                 pdue=pdup+140;
1750                 }
1751         udlb=(udl*7+7)/8;
1752         if (pdup+udlb>pdue) {
1753 size_t udl1,udlb1;
1754
1755                 udlb1=pdue-pdup;
1756                 udl1=(udlb1*8)/7;
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;
1760                 }
1761         else
1762                 error(_("Trailing garbage ignored in PDU data (UDL %d/7->%d/8, got %d) in: %s"),
1763                         udl,udlb,pdue-pdup,pduline);
1764         textp=text;
1765         inb=outb=0;
1766         inreg=0; /* GCC happiness */
1767         while (udl) {
1768                 if (!inb) {
1769                         inreg=*pdup++;
1770                         inb=8;
1771                         }
1772                 if (!outb) {
1773                         assert(textp<text+160);
1774                         *textp=0x00;
1775                         outb=7;
1776                         }
1777                 xb=MIN(inb,outb);
1778 #if 0
1779                 d4("inb=%d,outb=%d,xb=%d\n",inb,outb,xb);
1780 #endif
1781                 *textp|=((inreg>>(unsigned)(7-inb))&((1<<xb)-1))<<(unsigned)(8-outb);
1782                 inb-=xb; outb-=xb;
1783                 if (!outb) {
1784                         *textp=charconv_recv(*textp,textp-text);
1785                         textp++;
1786                         udl--;
1787                         }
1788                 }
1789         *textp=0;
1790         receive_text(text);
1791 }
1792
1793 static struct {
1794         char **sp;
1795         long *ip;
1796         const char *const msg;
1797         } numarg[]={
1798                 { &maxretry,&maxretryn,"maxretry" },
1799                 { &readtime,&readtimen,"readtime" },
1800                 { &chartime,&chartimen,"chartime" },
1801                 { &cmdtime ,&cmdtimen ,"cmdtime"  },
1802                 { &baud    ,&baudn    ,"baud"     },
1803         };
1804
1805 int main(int argc,char **argv)
1806 {
1807 char *s;
1808 int i,cmgf=-1 /* GCC happiness */;
1809 unsigned fatal=0;
1810 speed_t portbaud=0 /* GCC happiness */;
1811 enum modenum argsmode;
1812 unsigned parts=0;
1813
1814         if ((s=strrchr((pname=*argv),'/'))) pname=s+1;
1815
1816 #ifdef ENABLE_NLS
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);
1822 #endif
1823
1824 #ifdef HAVE_ATEXIT
1825         atexit(cleanup);
1826 #else
1827         error(_("atexit(3) not available at compilation time, device cleanup may be missed"));
1828 #endif
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;
1839                         continue;
1840                         }
1841                 mode=MODE_UNKNOWN;
1842                 break;
1843                 }
1844         argsmode=mode;
1845         processargs(argc,argv,_("<command-line>"));
1846         if ((s=getenv("HOME"))) {
1847 size_t l=strlen(s);
1848 char *buf=malloc(l+50);
1849
1850                 memcpy(buf,s,l);
1851                 strcpy(buf+l,CONFIG_HOME);
1852                 readfile(buf,1);
1853                 free(buf);
1854                 }
1855         readfile(CONFIG_MAIN,1);
1856         if (verbose>=1) {
1857                 if (argsmode)
1858                         error(_(".Detected mode \"%s\" from my program name \"%s\""),MODE_NAME(argsmode),pname);
1859                 else
1860                         error(_(".Automatic mode detection unsuccessul for my progam name \"%s\""),pname);
1861                 }
1862
1863         if (!mode)
1864                 error(_("!Operation mode unset, use --send or similiar command, see help (-h)"));
1865         error(_(".Running program in mode \"%s\""),MODE_NAME(mode));
1866         switch (mode) {
1867
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;
1873                 default: assert(0);
1874                 }
1875         cmdline_done();
1876         for (i=0;i<NELEM(nullcheck);i++) {
1877 const struct nullcheck *n=nullcheck+i;
1878
1879                 if (*n->var) continue;
1880                 if (n->reqd && !(MODE_BIT(mode)&n->reqd)) continue;
1881                 error(_("Missing parameter \"%s\""),_(n->name));
1882                 fatal++;
1883                 }
1884         if (fatal) error(_("!Previous %s considered unrecoverable"),(fatal==1?_("error"):_("errors")));
1885         emptyclean();
1886         if (!logname) logname=DEF_LOGNAME;
1887         if (!lockfile) lockfile=DEF_LOCKFILE;
1888         if (!device) device=DEF_DEVICE;
1889
1890         for (i=0;i<NELEM(numarg);i++) {
1891 char *serr;
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);
1897                 }
1898         if (readtimen==-1)
1899                 readtimen=(mode==MODE_SEND_MOBILDOCK?DEF_READTIME_MOBILDOCK:DEF_READTIME);
1900         if (mode==MODE_SEND_MOBILDOCK) mode=MODE_SEND;
1901
1902         if (!strchr(device,'/')) {
1903 size_t l=strlen(device);
1904                 chk(s=malloc(5+l+1));
1905                 strcpy(s,"/dev/");
1906                 strcpy(s+5,device);
1907                 free(device);
1908                 device=s;
1909                 }
1910         devicename=strrchr(device,'/')+1; assert(!!(devicename-1));
1911         for (i=0,s=lockfile;*s;s++) {
1912                 if (*s!='%') continue;
1913                 s++;
1914                 if (*s=='%') continue;
1915                 if (*s=='s') {
1916                         if (i) error(_("!Only one \"%%s\" permitted in lockfile format-string"));
1917                         i=1; continue;
1918                         }
1919                 error(_("!Invalid format-character '%c' in lockfile format-string, only \"%%s\" allowed"),*s);
1920                 }
1921         
1922         if (*logname) {
1923                 if (!(logf=fopen(logname,"a")))
1924                         error(_("^!Error opening log \"%s\" for append"),logname);
1925                 logmsg(_("Starting up: %s"),PACKAGE " " VERSION);
1926                 }
1927
1928         switch (mode) {
1929                 case MODE_SEND:
1930                         preparebody();
1931                         genpdu();
1932                         readbody=0;
1933                         break;
1934                 case MODE_LOGO_SEND:
1935                         logoread();
1936                         break;
1937                 case MODE_RING_SEND:
1938                         ringread();
1939                         break;
1940                 case MODE_RECEIVE: break;
1941                 default: assert(0);
1942                 }
1943         if (readbody)
1944                 error(_("Warning: -f / --file is forbidden with mode \"%s\""),MODE_NAME(mode));
1945
1946         switch (baudn) {
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;
1953                 default:
1954                         error(_("!Specified baudrate %ld is not supported"),baudn);
1955                 }
1956         if (verbose>=2) error(_(".Will use baudrate %ld with hexval 0x%X"),baudn,portbaud);
1957                 
1958         if (lockfile && *lockfile && VARPRINTF(lockreal,lockfile,devicename)>0) {
1959 time_t start,end;
1960                 if (verbose>=1) error(_(".Locking device \"%s\" by \"%s\".."),device,lockreal);
1961                 time(&start);
1962                 lockdevice(0);
1963                 time(&end);
1964                 if ((end-=start)>LOCKREPORT)
1965                         logmsg(_("Device lock succeeded after %ld seconds"),(long)end);
1966                 }
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);
1970         
1971         if (tcgetattr(devfd,&restios))
1972                 error(_("^Unable to get termios settings"));
1973         else {
1974                 restios.c_cflag=(restios.c_cflag&~(CBAUD|CBAUDEX))|B0|HUPCL;
1975                 restios_yes=1;
1976                 }
1977         tios.c_iflag=IGNBRK|IGNPAR|IXON|IXOFF;
1978         tios.c_oflag=0;
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));
1982         tios.c_cc[VTIME]=0;
1983         tios.c_cc[VMIN ]=1;
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"));
1991
1992         setalarm();
1993
1994 retryall:
1995                 devcmd("",NULL,"\r\nAT\033\032"); /* ESCAPE, CTRL-Z */
1996                 devcmd(NULL,NULL,"\r\nAT");
1997                 smscset();
1998                 if (mode==MODE_SEND || mode==MODE_RECEIVE) {
1999                         cmgf=-1;
2000                         do {
2001                                 if (!devcmd(NULL,NULL,"!\r\nAT+CMGF=0")) {
2002                                         if (!devcmd(NULL,NULL,"!\r\nAT+CMGF=1"))
2003                                                 { retrying(); continue; }
2004                 /* CMGF=1 */
2005                                         if (verbose>=1)
2006                                                 error(_(".Using AT+CMGF=1 (text mode).."));
2007                                         cmgf=1;
2008                                         }
2009                                 else {
2010                 /* CMGF=0 */
2011                                         if (verbose>=1)
2012                                                 error(_(".Using AT+CMGF=0 (PDU mode).."));
2013                                         cmgf=0;
2014                                         }
2015                                 } while (cmgf==-1);
2016                         }
2017                 switch (mode) {
2018                         case MODE_SEND:
2019                                 if (cmgf) {
2020                                         devcmd("\n> ",NULL,"\r\nAT+CMGS=\"%s\"",phone);
2021                                         s=devcmd(NULL,"\n+CMGS:","!~%s\032",body);
2022                                         }
2023                                 else {
2024                                         devcmd("\n> ",NULL,"\r\nAT+CMGS=%d",(strlen(pdusmsc)+strlen(pdudata))/2);
2025                                         s=devcmd(NULL,"\n+CMGS:","!~%s%s\032",pdusmsc,pdudata);
2026                                         }
2027                                 break;
2028                         case MODE_LOGO_SEND:
2029                         case MODE_RING_SEND: {
2030 struct hexdata *hd;
2031
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);
2038                                         free(hd);
2039                                         parts++;
2040                                         }
2041                                 } break;
2042                         case MODE_RECEIVE:
2043                                 restore="\r\nAT+CNMI=,0";
2044                                 devcmd(NULL,NULL,"\r\nAT+CNMI=,2");
2045                                 devcmd(NULL,NULL,"\r\nAT+CSDH=0");
2046                                 unlockdevice(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"));
2050                                 maxretryn=-1;
2051 #if RECEIVE_TEST
2052                 receive_headerparse(" \"+420602123456\",,\"99/10/25,03:21:03-00\"");
2053                 receive_accept("TESTBODY");
2054                 exit(EXIT_SUCCESS);
2055 #endif
2056                                 datawait(0);
2057                                 if (!lockdevice(1)) {
2058                                         if (verbose>=1)
2059                                                 error(_(".Dialout detected, waiting for lock.."));
2060                                         lockdevice(0);
2061                                         goto retryall;
2062                                         }
2063                                 d1("Lock-device succeeded\n");
2064                                 do {
2065                                         d1("Reading a message for us...\n");
2066                                         if (!(s=devcmd("\r","@+CMT:"," ")))
2067                                                 goto retryall;
2068                                         if (cmgf && !(i=receive_headerparse(s)))
2069                                                 error(_("Receive-header parsing failed on: %s"),s);
2070                                         if (!(s=devcmd("\r","@\n"," ")))
2071                                                 goto retryall;
2072                                         if (cmgf) {
2073                                                 if (i) receive_text(s);
2074                                                 }
2075                                         else receive_pdu(s);
2076                                         if (!devcmd("\n",NULL," ")) /* eat last '\n' */
2077                                                 goto retryall;
2078                                         } while (datawait(1));
2079                                 goto retryall;
2080                                 break;
2081                         default: assert(0);
2082                         }
2083                 if (!s) { retrying(); goto retryall; }
2084
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);
2089                 }
2090         devcmd(NULL,NULL,"\r\nAT");
2091
2092         logmsg(_("SMS sent (after %d retries), %d part(s)"),retrycnt,parts);
2093         return(EXIT_SUCCESS);
2094 }