Device reinitialized before any command retry ("retryall" label moved)
[mdsms.git] / mdsms.c
1 #define WANT_DECLARATIONS 1
2 #include "config.h"
3 #ifndef lint
4 static char rcsid[] ATTR_UNUSED = "$Id$";
5 #endif
6
7 #include "setup.h"
8
9 #ifdef HAVE_STDIO_H
10 #include <stdio.h>
11 #endif
12 #ifdef HAVE_STDLIB_H
13 #include <stdlib.h>
14 #endif
15 #ifdef HAVE_STRING_H
16 #include <string.h>
17 #endif
18 #ifdef HAVE_SIGNAL_H
19 #include <signal.h>
20 #endif
21 #ifdef HAVE_STDARG_H
22 #include <stdarg.h>
23 #endif
24 #ifdef HAVE_LIMITS_H
25 #include <limits.h>
26 #endif
27 #ifdef HAVE_CTYPE_H
28 #include <ctype.h>
29 #endif
30 #ifdef HAVE_TERMIOS_H
31 #include <termios.h>
32 #endif
33 #ifdef HAVE_UNISTD_H
34 #include <unistd.h>
35 #endif
36 #ifdef HAVE_ASSERT_H
37 #include <assert.h>
38 #endif
39 #ifdef HAVE_SYS_TYPES_H
40 #include <sys/types.h>
41 #endif
42 #ifdef HAVE_SYS_WAIT_H
43 #include <sys/wait.h>
44 #endif
45 #ifdef HAVE_SYS_STAT_H
46 #include <sys/stat.h>
47 #endif
48 #ifdef HAVE_FCNTL_H
49 #include <fcntl.h>
50 #endif
51 #ifdef HAVE_ERRNO_H
52 #include <errno.h>
53 #endif
54 #ifdef HAVE_TIME_H
55 #include <time.h>
56 #endif
57 #ifdef HAVE_SYS_TIME_H
58 #include <sys/time.h>
59 #endif
60 #ifdef HAVE_SYS_POLL_H
61 #include <sys/poll.h>
62 #endif
63 #ifdef HAVE_LOCALE_H
64 #include <locale.h>
65 #endif
66
67 #ifdef HAVE_GETOPT_LONG
68 #include <getopt.h>
69 #else
70 #include "getopt.h"
71 #endif
72
73
74 /* Always override possible system defintions as it is safe (used by glib) */
75 #undef MAX
76 #define MAX(a,b) ((a)>(b)?(a):(b))
77 #undef MIN
78 #define MIN(a,b) ((a)<(b)?(a):(b))
79
80 #define NELEM(x) (sizeof((x))/sizeof(*(x)))
81
82 #ifndef DEBUG
83 #define dbg(cmd)
84 #else
85 #define dbg(cmd) cmd
86 #endif
87 /* ANSI C does not allow macro with variable arguments */
88 #define dO stderr
89 #define dB(a) dbg(fprintf a)
90
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))
99
100 static const char version[]="Mobile Device SMS tool (" PACKAGE " " VERSION ")\n";
101
102 static int verbose
103 #ifdef DEBUG
104         =0xFFFF
105 #endif
106         ;
107 static char *pname;
108 static int dis_cleanup=0,devfd=-1;
109
110 static char *phone,*device,*logname,*lockfile,*smsmode,*pdusmscmode,*smsc,*maxretry,*readtime,*chartime,*cmdtime,*baud,*restore;
111 static int readbody;
112 static long maxretryn=DEF_MAXRETRY,readtimen=-1,chartimen=DEF_CHARTIME,cmdtimen=DEF_CMDTIME,baudn=DEF_BAUD;
113 #ifdef HAVE_CRTSCTS
114 static int handshake_rtscts;
115 static unsigned handshake_stamp;
116 #else
117 #define handshake_rtscts (0)
118 #endif
119 static enum {
120         FSM_AUTO=0,
121         FSM_PDU,
122         FSM_TEXT
123         } force_smsmode=FSM_AUTO;
124 static enum {
125         FPSM_AUTO=0,
126         FPSM_COUNT_IN,
127         FPSM_COUNT_OUT,
128         FPSM_NONE
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 */
135 static char *body;
136 /* --logo-send specific */
137 static char *logoname,*gsmnet;
138 /* --ring-send specific */
139 static char *ringname;
140
141 static enum modenum {
142   MODE_UNKNOWN=0,
143 /* must differ from regular char-s */
144   MODE_FIRST         =0x3400,
145         MODE_SEND          =MODE_FIRST+0, /* --send / --send-mobildock */
146         MODE_SEND_MOBILDOCK=MODE_FIRST+1, /* --send-mobildock in before readtimen is set */
147         MODE_RECEIVE       =MODE_FIRST+2, /* --receive */
148         MODE_LOGO_SEND     =MODE_FIRST+3, /* --logo-send */
149         MODE_RING_SEND     =MODE_FIRST+4  /* --ring-send */
150         } mode=MODE_UNKNOWN;
151 #define MODE_ORDER(x) ((x)-MODE_FIRST)
152 #define MODE_NAME(x) (longopts[MODE_ORDER((x))].name)
153 #define MODE_BIT(x) (1<<MODE_ORDER((x)))
154
155 static unsigned mode_stamp;
156
157 /* pdusmsc variable has to be filled in */
158 #define NEED_PDUSMSC() (mode==MODE_SEND)
159
160 static char *devicename; /* path stripped */
161 static char lockreal[512],locked;
162
163 static struct termios restios,tios;
164 static char restios_yes;
165 static FILE *logf;
166
167 static void vlogmsg(char pm,char fatal,const char *fmt,va_list ap) ATTR_PRINTFORMAT(3,0);
168 static void vlogmsg(char pm,char fatal,const char *fmt,va_list ap)
169 {
170 time_t stamp;
171 char *ctm,*s;
172 pid_t mypid=-1;
173 char host[LINE_MAX];
174
175         if (!logf) return;
176         if (mypid==-1) {
177                 mypid=getpid();
178                 if (gethostname(host,sizeof(host))) strcpy(host,_("<ERROR>"));
179                 }
180         time(&stamp);
181         ctm=ctime(&stamp);
182         if ((s=strchr(ctm,'\n'))) *s='\0';
183         fprintf(logf,"%s %s %s[%d]: ",ctm,host,pname,mypid);
184         vfprintf(logf,fmt,ap);
185         if (pm) { fputs(": ",logf); fputs(strerror(errno),logf); }
186         if (fatal!='\n') fputc((fatal=='.'?'.':'!'),logf);
187         fputc('\n',logf);
188         fflush(logf);
189 }
190
191 static void logmsg(const char *fmt,...) ATTR_PRINTFORMAT(1,2);
192 static void logmsg(const char *fmt,...)
193 {
194 va_list ap;
195         va_start(ap,fmt);
196         vlogmsg(0,'\n',fmt,ap);
197         va_end(ap);
198 }
199
200 static void error(const char *fmt,...) ATTR_PRINTFORMAT(1,2);
201 static void error(const char *fmt,...)
202 {
203 va_list ap;
204 char fatal,pm;
205
206         if ((pm=(*fmt=='^'))) fmt++;
207         fatal=*fmt;
208         if (fatal=='!' || fatal=='.' || fatal=='\n') fmt++;
209         else fatal=0;
210
211         fprintf(stderr,"%s: ",pname);
212         va_start(ap,fmt);
213         vfprintf(stderr,fmt,ap);
214         if (fatal=='!') vlogmsg(pm,fatal,fmt,ap);
215         va_end(ap);
216         if (pm) { fputs(": ",stderr); fputs(strerror(errno),stderr); }
217         if (fatal!='\n') fputc((fatal=='.'?'.':'!'),stderr);
218         fputc('\n',stderr);
219         if (fatal=='!') exit(EXIT_FAILURE);
220 }
221
222 static void chk(const void *p)
223 {
224         if (p) return;
225         error(_("!Virtual memory exhausted"));
226 }
227
228 static char *devcmd(const char *term,const char *catch,const char *send,...) ATTR_PRINTFORMAT(3,4);
229
230 static void unlockdevice(int hard)
231 {
232         d2("unlockdevice(), locked=%d\n",locked);
233         if (!locked || !*lockreal) return;
234         if (!hard && locked>1) { locked--; return; }
235         d2("Removing lockfile \"%s\"\n",lockreal);
236         if (unlink(lockreal))
237                 error(_("^Error removing my device lockfile \"%s\""),lockreal);
238         locked=0;
239 }
240
241 static void cleanup(void)
242 {
243         d1("cleanup()\n");
244         if (dis_cleanup) return;
245         if (restore) {
246 char *cmd=restore;
247                 restore=NULL;
248                 devcmd(NULL,NULL,"\r\nAT");
249                 devcmd(NULL,NULL,cmd);
250                 devcmd(NULL,NULL,"\r\nAT");
251                 }
252         if (restios_yes) {
253                 if (tcsetattr(devfd,TCSANOW,&restios))
254                         error(_("^Error restoring termios for device"));
255                 restios_yes=0;
256                 }
257         unlockdevice(1);
258         dis_cleanup=1;
259         exit(EXIT_FAILURE);
260 }
261
262 static void usage(void)
263 {
264         fprintf(stderr,_("\
265 \n\
266 %s\
267 \n\
268 Usage: %s [-c|--config <cfgfile>] [-d|--device <device>]\n\
269              [-L|--log <file>] [-l|--lockfile <lock>]\n\
270              [-b|--baud <rate>] [-x|--xonxoff] [-C|--rtscts]\n\
271              [-M|--smsmode <mode>] [-P|--pdusmscmode <mode>]\n\
272              [-s|--smsc <smsc #>] [-m|--maxretry <#>]\n\
273              [-r|--readtime <sec>] [-t|--chartime <msec>] [-T|--cmdtime <msec>]\n\
274              [-v|--verbose] [-h|--help] [-V|--version]\n\
275              {--send | --send-mobildock | --receive | --logo-send}\n\
276   --send / --send-mobildock:\n\
277              [-f|--file] <dest. phone> <msg text|msg filename>\n\
278   --receive:\n\
279              <command name>\n\
280   --logo-send:\n\
281              <dest. phone> <logo filename> [<GSMnet id>]\n\
282   --ring-send:\n\
283              <dest. phone> <ring filename>\n\
284 \n\
285  -c, --config\tRead this additional config file\n\
286 \t\t(def. \"%s\" and \"$HOME%s\")\n\
287  -d, --device\tMobile on this serial device (def. \"%s\")\n\
288  -L, --log\tLog all important messages to this file (def. \"%s\")\n\
289  -l, --lockfile\tLock serial port by this file, \"%%s\" is basename of device\n\
290 \t\t(def. \"%s\")\n\
291  -b, --baud\tSet baudrate, 2400-57600 supported (def. %d)\n\
292  -x, --xonxoff\tUse XON/XOFF (AKA software) serial port handshaking - default\n\
293  -C, --rtscts\tUse RTS/CTS (AKA hardware) serial port handshaking%s\n\
294  -M, --smsmode\tForce SMS as: \"pdu\" or 0: PDU mode, \"text\" or 1: text mode\n\
295  -P, --pdusmscmode\tForce PDU as: \"count-in\", \"count-out\", \"none\"\n\
296  -s, --smsc\tUse this SMS Center number (def. query from mobile)\n\
297  -m, --maxretry\tMaximum retries of any command before giving up (def. %d)\n\
298  -r, --readtime\tSeconds for maximum wait time for response\n\
299 \t\t(def. %ds standard, %ds for MobilDock modes,\n\
300 \t\t multiplied %dx for long cmds)\n\
301  -t, --chartime\tMilliseconds between each char (def. %dms)\n\
302  -T, --cmdtime\tMilliseconds before each whole AT command (def. %dms)\n\
303  -v, --verbose\tIncrease verbosity level, more \"-v\"s give more messages\n\
304  -h, --help\tPrint a summary of the options\n\
305  -V, --version\tPrint the version number\n\
306 \n\
307 --send / --send-mobildock:\n\
308  -f, --file\tRead contents of message from file instead\n\
309 --receive:\n\
310  <command name>\tProgram to run on receive, message will be on stdin\n\
311 \t\tFollowing substitutes are recognized:\n\
312 \t\t%%p - source phone number\n\
313 \t\t%%T - timestamp from SMSC as # of seconds from 1970 (-1 if invalid)\n\
314 \t\t%%t - ctime(3) style timestamp (e.g. \"Wed Jun 30 21:49:08 1993\"),\n\
315 \t\t     empty string if invalid\n\
316 \t\t%%s - originating SMSC number, if available (else empty)\n\
317 --logo-send:\n\
318  <GSMnet id>\t* Oper. logo: Enter custom network code MccMnc, e.g. 23002\n\
319 \t\t* Oper. logo: Specify \"%s\" to read network code from NOL file\n\
320 \t\t* Group gfx : Specify \"%s\" to send logo as group graphics\n\
321 \n\
322 You may need to use the following line to catch all of this help text:\n\
323 ./mdsms -h 2>&1|more\n\
324 \n"),version,PACKAGE,CONFIG_MAIN,CONFIG_HOME,DEF_DEVICE,DEF_LOGNAME,DEF_LOCKFILE,DEF_BAUD,
325 #ifdef HAVE_CRTSCTS
326                 "",
327 #else
328                 _("\n\t\t(Not supported on this platform!)"),
329 #endif
330 DEF_MAXRETRY,DEF_READTIME,DEF_READTIME_MOBILDOCK,EXT_READTIME,DEF_CHARTIME,DEF_CMDTIME,
331 WORD_NET,WORD_GROUP);
332         exit(EXIT_FAILURE);
333 }
334
335 static const struct option longopts[]={
336 /* Modes has to be in-order on exact positions */
337 {"send"          ,0,0,MODE_SEND},
338 {"send-mobildock",0,0,MODE_SEND_MOBILDOCK},
339 {"receive"       ,0,0,MODE_RECEIVE},
340 {"logo-send"     ,0,0,MODE_LOGO_SEND},
341 {"ring-send"     ,0,0,MODE_RING_SEND},
342 /* Mode aliases may follow in no particular order *
343  * as long as no non-mode options is between them */
344 {"send-md"       ,0,0,MODE_SEND_MOBILDOCK},
345 {"recv"          ,0,0,MODE_RECEIVE},
346 {"logo"          ,0,0,MODE_LOGO_SEND},
347 {"ring"          ,0,0,MODE_RING_SEND},
348 {"config"      ,1,0,'c'},
349 {"device"      ,1,0,'d'},
350 {"log"         ,1,0,'L'},
351 {"lockfile"    ,1,0,'l'},
352 {"baud"        ,1,0,'b'},
353 {"xonxoff"     ,0,0,'x'},
354 {"rtscts"      ,0,0,'C'},
355 {"smsmode"     ,1,0,'M'},
356 {"pdusmscmode" ,1,0,'P'},
357 {"smsc"        ,1,0,'s'},
358 {"maxretry"    ,1,0,'m'},
359 {"readtime"    ,1,0,'r'},
360 {"chartime"    ,1,0,'t'},
361 {"cmdtime"     ,1,0,'T'},
362 {"file"        ,0,0,'f'},
363 {"verbose"     ,0,0,'v'},
364 {"help"        ,0,0,'h'},
365 {"version"     ,0,0,'V'},
366 {NULL          ,0,0,0  }};
367
368 static void processargs(int argp,char **args,const char *from);
369
370 static char *cfgstack[MAXCFGLOOP];
371 static unsigned cfgstacki=0;
372
373 static void chkfclose(FILE *f,const char *fname)
374 {
375         if (fclose(f))
376                 error(_("^Error closing \"%s\""),fname);
377 }
378
379 static long getfilesize(FILE *f,const char *fname)
380 {
381 long size;
382
383         if (fseek(f,0,SEEK_END))
384                 error(_("^Error seeking to end of \"%s\""),fname);
385         if ((size=ftell(f))<0)
386                 size=-1,error(_("^Error measuring length of \"%s\""),fname);
387         rewind(f);
388         return(size);
389 }
390
391 static void readfile(const char *fname,char quiet)
392 {
393 FILE *f;
394 size_t got;
395 char *args[MAXCFGARGS],*d,*s,blank,quote;
396 unsigned argp;
397 char *buf;
398 long size;
399 static unsigned tot=0;
400
401         if (tot++>=MAXCFGNUM) {
402                 if (tot==MAXCFGNUM+1) error(_("Too many config files to read, max is %d, break-out"),MAXCFGNUM);
403                 return;
404                 }
405         if (!(f=fopen(fname,"rt"))) {
406                 if (!quiet) error(_("^Can't open config file \"%s\" for r/o"),fname);
407                 return;
408                 }
409                 
410         if (verbose>=2) error(_(".Reading config file \"%s\""),fname);
411         if ((size=getfilesize(f,fname))==-1) size=0;
412         if (size>MAXCONFIG) 
413                 error(_("File \"%s\" is too long, read only %d bytes"),fname,MAXCONFIG);
414         chk(buf=malloc((size?size:MAXCONFIG)+1));
415         got=fread(buf,1,(size?size:MAXCONFIG),f);
416         if (size && got!=size)
417                 error(_("File \"%s\" read error, got only %u bytes of %ld"),fname,got,size);
418         chkfclose(f,fname);
419         buf[got]='\0';
420         args[0]=pname;
421         for (argp=1,d=s=buf,blank=1,quote=0;s<buf+got;s++) {
422 char c=*s;
423
424                 if (!quote && isspace(c)) {
425                         if (!blank) {
426                                 *d='\0';
427                                 blank=1;
428                                 if (verbose>=2) error(_("\nConfig \"%s\": arg#%d: %s"),fname,argp-1,args[argp-1]);
429                                 }
430                         continue;
431                         }
432                 if (blank) {
433                         if (argp>=NELEM(args)-1) {
434                                 error(_("Too many arguments in \"%s\", from offset %d ignored"),fname,s-buf);
435                                 break;
436                                 }
437                         args[argp++]=s;
438                         d=s;
439                         blank=0;
440                         }
441                 if (c=='\\') { *d++=*++s; continue; }
442                 if (c=='"' || c=='\'') {
443                         if (!quote   ) { quote=c; continue; }
444                         if ( quote==c) { quote=0; continue; }
445                         /* FALLTHRU */
446                         }
447                 *d++=c;
448                 }
449         args[argp]=NULL;
450         processargs(argp,args,fname);
451         free(buf);
452 }
453
454 static struct argstack {
455         struct argstack *next;
456         int num,offset;
457         const char *from;
458         char *arg[1];
459         } *argstack;
460
461 static struct argstack **argstack_tail=&argstack;
462 static size_t lastargstack_len;
463 static const char *lastargstack_from;
464 static int lastargstack_index;
465
466 static size_t argstack_size;
467 static int argstack_num;
468
469 static void pushargstack(char **args,int num,int offset,const char *from,char stack)
470 {
471 struct argstack *as;
472 int i;
473
474         if (!num) return;
475         assert(num>=1);
476         chk(as=malloc(sizeof(*as)+sizeof(as->arg)*(num-1)));
477         as->num=num;
478         as->offset=offset;
479         if (!from) as->from=NULL;
480         else chk(as->from=strdup(from));
481         for (i=0;i<num;i++) {
482                 chk(as->arg[i]=strdup(args[i]));
483                 argstack_size+=strlen(args[i]);
484                 }
485         argstack_num+=num;
486         if (stack) {
487                 as->next=argstack;
488                 argstack=as;
489                 }
490         else {
491                 as->next=NULL;
492                 *argstack_tail=as;
493                 argstack_tail=&as->next;
494                 }
495 }
496
497 static void pushargstack_one(char *s,char stack)
498 { pushargstack(&s,1,0,NULL,stack); }
499
500 static char *nextargstack(void)
501 {
502 static int order=0;
503 char *r;
504
505         if (argstack && order==argstack->num) {
506 struct argstack *as=argstack;
507                 if (!(argstack=as->next))
508                         argstack_tail=&argstack;
509                 order=0;
510                 free((char *)as->from);
511                 lastargstack_from=NULL;
512                 free(as);
513                 }
514         if (!argstack) {
515                 assert(!argstack_num); assert(!argstack_size);
516                 return(NULL);
517                 }
518         assert(order<argstack->num);
519         lastargstack_index=argstack->offset+order;
520         r=argstack->arg[order++];
521         assert(argstack_num>0); argstack_num--;
522         lastargstack_len=strlen(r);
523         assert(argstack_size>=lastargstack_len); argstack_size-=lastargstack_len;
524         lastargstack_from=argstack->from;
525         return(r);
526 }
527
528 static char *glueargstack(size_t *destlenp,const char *glue)
529 {
530 size_t gluel=(glue?strlen(glue):0),destlen;
531 char *dest,*d,*s;
532
533         if (!argstack_num) {
534                 chk(dest=strdup(""));
535                 if (destlenp) *destlenp=0;
536                 return(dest);
537                 }
538         destlen=argstack_size+(argstack_num-1)*gluel;
539         if (destlenp) *destlenp=destlen;
540         chk(dest=malloc(destlen+1));
541         for (d=dest;(s=nextargstack());) {
542                 memcpy(d,s,lastargstack_len);
543                 free(s);
544                 d+=lastargstack_len;
545                 if (!argstack_num) break;
546                 if (!glue) continue;
547                 memcpy(d,glue,gluel);
548                 d+=gluel;
549                 assert(d<=dest+destlen);
550                 }
551         assert(!argstack_num);
552         assert(d==dest+destlen);
553         *d='\0';
554         return(dest);
555 }
556
557 static struct {
558         const char c;
559         char **const var;
560         unsigned stamp;
561         } optset[]={
562                 { 'd',&device       },
563                 { 'L',&logname      },
564                 { 'l',&lockfile     },
565                 { 'b',&baud         },
566                 { 'M',&smsmode      },
567                 { 'P',&pdusmscmode  },
568                 { 's',&smsc         },
569                 { 'm',&maxretry     },
570                 { 'r',&readtime     },
571                 { 't',&chartime     },
572                 { 'T',&cmdtime      },
573         };
574
575 static void processargs(int argp,char **args,const char *from)
576 {
577 int optc;
578 static unsigned seq=0;
579 int i;
580
581         seq++;
582         optarg=NULL; optind=0; /* FIXME: Possible portability problem. */
583         while ((optc=getopt_long(argp,args,"c:d:L:l:b:xCM:P:s:m:r:t:T:fvhV",longopts,NULL))!=EOF) switch (optc) {
584                 case 'c':
585                         if (cfgstacki>=NELEM(cfgstack)) {
586                                 error(_("Looping (%d) during attempt to read config file \"%s\", break-out"),NELEM(cfgstack),from);
587                                 break;
588                                 }
589                         chk(cfgstack[cfgstacki++]=strdup(optarg));
590                         break;
591                 case 'd': case 'L': case 'b': case 'l': case 'M': case 'P': case 's': case 'm': case 'r': case 't': case 'T':
592                         for (i=0;i<NELEM(optset);i++)
593                                 if (optset[i].c==optc) {
594                                         if (optset[i].stamp && optset[i].stamp!=seq) {
595                                                 assert(!!*optset[i].var);
596                                                 break;
597                                                 }
598                                         free(*optset[i].var);
599                                         chk(*optset[i].var=strdup(optarg));
600                                         optset[i].stamp=seq;
601                                         break;
602                                         }
603                         assert(i<NELEM(optset));
604                         break;
605                 case 'x': case 'C':
606 #ifdef HAVE_CRTSCTS
607                         if (handshake_stamp && handshake_stamp!=seq) break;
608                         handshake_rtscts=(optc=='C');
609                         handshake_stamp=seq;
610 #else
611                         if (optc=='C')
612                                 error(_("!RTS/CTS handshake NOT supported on this platform! Occured during parsing option %d from \"%s\""),optind-1,from);
613 #endif
614                         break;
615                 case MODE_SEND:
616                 case MODE_SEND_MOBILDOCK:
617                 case MODE_RECEIVE:
618                 case MODE_LOGO_SEND:
619                 case MODE_RING_SEND:
620                         if (mode_stamp && mode_stamp!=seq) break;
621                         mode=optc;
622                         mode_stamp=seq;
623                         break;
624                 case 'f':
625                         readbody++;
626                         break;
627                 case 'v':
628 #ifndef DEBUG   /* prevent suppositious overflow */
629                         verbose++;
630 #endif
631                         break;
632                 case 'V':
633                         fprintf(stderr,version);
634                         exit(EXIT_FAILURE);
635                 default:
636                         if (optc!='h')
637                                 error(_("\nLast getopt(3) error occured during parsing option %d from \"%s\"! Follows help:"),optind-1,from);
638                         usage();
639                         break;
640                 }
641         pushargstack(args+optind,argp-optind,optind,from,1);
642         while (cfgstacki) {
643 char *s=cfgstack[--cfgstacki];
644
645                 assert(cfgstacki>=0);
646                 readfile(s,0);
647                 free(s);
648                 assert(cfgstacki>=0 && cfgstacki<NELEM(cfgstack));
649                 }
650 }
651
652 static const struct nullcheck {
653         char **var;
654         enum modenum reqd;
655         const char *name;
656         } nullcheck[]={
657                 {&phone,MODE_BIT(MODE_SEND)|MODE_BIT(MODE_SEND_MOBILDOCK)|MODE_BIT(MODE_LOGO_SEND),
658                         N_("destination phone number")},
659                 {&logoname,MODE_BIT(MODE_LOGO_SEND),N_("logo filename")},
660                 {&ringname,MODE_BIT(MODE_RING_SEND),N_("ring filename")},
661                 {&body,MODE_BIT(MODE_RECEIVE),N_("body text")}, /* we allow empty bodies for SENDs */
662 #if 0
663                 {&gsmnet,MODE_BIT(MODE_LOGO_SEND),N_("GSM operator network code")},
664                 {&device,0,N_("device for communication")},
665 #endif
666         };
667 static char **emptycheck[]={&logname,&smsc,&logoname,&gsmnet};
668
669 static inline void emptyclean(void)
670 {
671 int i;
672
673         for (i=0;i<NELEM(emptycheck);i++)
674                 if (*emptycheck[i] && !**emptycheck[i]) {
675                         free(*emptycheck[i]);
676                              *emptycheck[i]=NULL;
677                         }
678 }
679
680 static inline void cmdline_done(void)
681 {
682 char *s;
683         while ((s=nextargstack())) {
684                 error(_("\nExcessive option %d from \"%s\" ignored: %s"),
685                         lastargstack_index,lastargstack_from,s);
686                 free(s);
687                 }
688         emptyclean();
689 }
690
691 static char *check_phone(const char *phone)
692 {
693 const char *s,*s1;
694 static char err[LINE_MAX];
695
696         for (s=s1=(phone+(*phone=='+'));*s && s-s1<MAXNUMLEN;s++)
697                 if (!isdigit(*s)) {
698                         VARPRINTF2(err,_("Invalid digit '%c' in phone number - at offset %d"),
699                                 *s,s-phone);
700                         return(err);
701                         }
702         if (!*s) return(NULL);
703         VARPRINTF2(err,_("Phone number too long (%d), max. %d digits allowed"),
704                 strlen(s1),MAXNUMLEN);
705         return(err);
706 }
707
708 static void cmdline_phone(void)
709 {
710         if (!phone && (phone=nextargstack())) {
711 char *s;
712
713                 if ((s=check_phone(phone)))
714                         error(_("!%s in option %d from \"%s\": %s"),
715                                         s,lastargstack_index,lastargstack_from,phone);
716                 }
717 }
718
719 static inline void cmdline_receive(void)
720 {
721 char *s;
722
723         if (!body && argstack_num) {
724                 body=glueargstack(&bodylen," ");
725                 for (s=body;(s=strchr(s,'%'));s++)
726                         switch (*++s) {
727                                 case 'p': case 'T': case 't': case 's': break;
728                                 default:
729                                         error(_("Unknown formatsymbol '%c' (use \"%%%%%c\" to fix it) at pos %d in: %s"),
730                                                 *s,*s,s-body,body);
731                                 }
732                 }
733 }
734
735 static inline void cmdline_send(void)
736 {
737         cmdline_phone();
738         if (!body && argstack_num)
739                 body=glueargstack(&bodylen," ");
740 }
741
742 static inline void cmdline_logo_send(void)
743 {
744 char *ogsmnet;
745
746         cmdline_phone();
747         if (!logoname) logoname=nextargstack();
748         if (!gsmnet && (ogsmnet=nextargstack())) {
749 char *s,*d,e=0;
750
751                 chk(gsmnet=strdup(ogsmnet));
752                 if (strtrycasecmp(gsmnet,WORD_NET) && strtrycasecmp(gsmnet,WORD_GROUP)) {
753                         for (d=s=gsmnet;*s;s++) {
754                                 if (isdigit(*s)) { *d++=*s; continue; }
755                                 if (isspace(*s)) continue;
756                                 error(_("\nInvalid characted '%c' in GSMnet at offs %d: %s"),
757                                         *s,s-gsmnet,ogsmnet);
758                                 e=1;
759                                 break;
760                                 }
761                         if ((d-gsmnet)!=5) {
762                                 error(_("\nGSMnet is required to have exactly 5 digits or to be\n\
763 either \"%s\" or \"%s\", but found length %d: %s"),
764                                         WORD_NET,WORD_GROUP,d-gsmnet,ogsmnet);
765                                 e=1;
766                                 }
767                         if (!e) *d='\0';
768                         else {
769                                 error(_("\nGSMnet option %d from \"%s\" rejected due to previous errors: %s"),
770                                         lastargstack_index,lastargstack_from,ogsmnet);
771                                 free(gsmnet);
772                                 gsmnet=NULL;
773                                 }
774                         }
775                 }
776 }
777
778 static inline void cmdline_ring_send(void)
779 {
780         cmdline_phone();
781         if (!ringname) ringname=nextargstack();
782 }
783
784 static void lockclose(int fd)
785 {
786         if (close(fd))
787                 error(_("Error closing lockfile \"%s\""),lockreal);
788 }
789
790 static int lockdevice(int attempt)
791 {
792 int fd=-1;
793 char buf[64];
794 ssize_t got;
795 int delay=0;
796 char empty=0;
797 pid_t pid;
798
799         d2("lockdevice(), locked=%d\n",locked);
800         if (locked) return (++locked);
801         for (;;) {
802                 if (fd!=-1) lockclose(fd);
803 recheck:
804                 if (delay) sleep(delay);
805                 delay=DEVLOCK_PERIOD;
806                 if (verbose>=3) error(_(".Checking the lockfile \"%s\".."),lockreal);
807                 if ((fd=open(lockreal,O_RDONLY))==-1) break;
808                 if ((got=read(fd,buf,sizeof(buf)-1))<=0) {
809 isempty:
810                         if (empty>=DEVLOCK_MAXEMPTY) {
811                                 error(_(".Lockfile \"%s\" is still not valid, removing it"),lockreal);
812                                 goto remove;
813                                 }
814                         empty++;
815                         continue;
816                         }
817                 assert(got<sizeof(buf));
818                 buf[got]='\0';
819                 if (sscanf(buf,"%d",&pid)!=1) goto isempty;
820                 empty=0;
821                 errno=0;
822                 if (kill(pid,0) && errno!=ESRCH && errno!=EPERM)
823                         error(_("^Error during checking consciousness of PID %d"),pid);
824                 if (errno!=ESRCH) {
825                         if (attempt) return(0);
826                         continue;
827                         }
828                 error(_(".Lockfile \"%s\" is stale (PID %d), removing it"),lockreal,pid);
829 remove:
830                 lockclose(fd);
831                 if (unlink(lockreal))
832                         error(_("^Error removing foreign lockfile \"%s\""),lockreal);
833                 break;
834                 }
835         errno=0;
836         if ((fd=open(lockreal,O_WRONLY|O_CREAT|O_EXCL,0644))==-1) {
837                 if (errno==EEXIST) goto recheck;
838                 error(_("^!Error creating lockfile \"%s\""),lockreal);
839                 }
840         locked=1;
841         got=VARPRINTF(buf,"%010d\n",getpid()); assert(got==11);
842         if (write(fd,buf,got)!=got)
843                 error(_("^!Error writing data to lockfile \"%s\""),lockreal);
844         lockclose(fd);
845         return((locked=1));
846 }
847
848 static char wasalarm=0;
849 static void sigalarm(int signo);
850
851 static void setalarm(void)
852 {
853         signal(SIGALRM,(RETSIGTYPE (*)(int))sigalarm);
854 #ifdef HAVE_SIGINTERRUPT
855         siginterrupt(SIGALRM,1);
856 #endif
857 }
858
859 static void sigalarm(int signo)
860 {
861         setalarm();
862         wasalarm=1;
863         if (verbose>=1) error(_("Timed out"));
864 }
865
866 static void blocking(char yes)
867 {
868 static char state=-1;
869         if (state==yes) return;
870         if (fcntl(devfd,F_SETFL,(yes?0:O_NONBLOCK)))
871                 error(_("^!fcntl() on device for %s mode"),(yes?_("blocking"):_("non-blocking")));
872         state=yes;
873 }
874
875 static const char *record,*recordend;
876 static char *catchdata;
877 static size_t catchdatal,catchdatasiz;
878
879 static const char *reform(const char *s,int slot);
880 static void catched(const char *end,char edata)
881 {
882 size_t len;
883 const char *p;
884
885         if (!record) return;
886         assert(end>=record);
887         p=memchr(record,edata,end-record);
888         if ((len=(p?p:end)-record)) {
889                 if (!catchdata)
890                         chk(catchdata=malloc((catchdatasiz=LINE_MAX)));
891                 if (catchdatal+len>catchdatasiz)
892                         chk(catchdata=realloc(catchdata,
893                                 (catchdatasiz=(catchdatal+len)*2)));
894                 memcpy(catchdata+catchdatal,record,len);
895                 catchdatal+=len;
896                 }
897         record   =(p?NULL:end);
898         recordend=(p?p   :end);
899         assert(catchdatal<=catchdatasiz);
900 }
901
902 static int retrycnt=0;
903 static void retrying(void)
904 {
905         if (maxretryn>=0 && ++retrycnt>=maxretryn) error(_("!Maximum command retry count (%ld) exceeded"),maxretryn);
906         if (verbose>=2) error(_(".Retrying phase, %d out of %ld.."),retrycnt,maxretryn);
907 }
908
909 static const char *reform(const char *s,int slot)
910 {
911 static struct formslot {
912         char *s;
913         size_t l;
914         } arr[3];
915 char c,*d;
916 struct formslot *fs;
917
918         assert(slot>=0 && slot<NELEM(arr));
919         if (!s) return(_("<unset>"));
920         if (!(fs=&arr[slot])->s)
921                 chk(fs->s=malloc(fs->l=LINE_MAX));
922         d=fs->s;
923         for (*d++='"';(c=*s);s++) {
924                 if (d>=fs->s+fs->l-10) {
925 off_t o=d-fs->s;
926                         chk(fs->s=realloc(fs->s,(fs->l=(fs->l?fs->l*2:LINE_MAX))));
927                         d=fs->s+o;
928                         }
929                 if (c!='\\' && c!='"' && isprint(c)) { *d++=c; continue; }
930                 *d++='\\';
931                 switch (c) {
932                         case '\\': case '"': *d++=c; break;
933                         case '\n': *d++='n'; break;
934                         case '\r': *d++='r'; break;
935                         case '\032': *d++='Z'; break;
936                         case '\033': *d++='e'; break;
937                         default:
938                                 d+=sprintf(d,"x%02X",(unsigned char)c);
939                                 break;
940                         }
941                 }
942         *d++='"'; *d='\0';
943         return(fs->s);
944 }
945
946 static char devcmd_empty_return='\0'; /* returned as catch when only newlines found */
947
948 static char *devcmd(const char *term,const char *catch,const char *send,...) ATTR_PRINTFORMAT(3,4);
949 static char *devcmd(const char *term,const char *catch,const char *send,...)
950 {
951 size_t l,bufl2,terml,catchl=0 /* GCC happiness */,fragl,offs;
952 static char buf[LINE_MAX];
953 static size_t bufl;
954 ssize_t got;
955 char *hit,*s;
956 va_list ap;
957 char errout,extend,catch_any,edata;
958 long alarmtime;
959 const char *osend;
960 static const char emptystring[]="";
961 size_t discard;
962
963         if (!term) term="\nOK\n";
964         if (!strcmp(send," ")) send=NULL; /* GCC formatstring-check workaround */
965         if (verbose>=2) error(_(".devcmd(sendfmt=%s,term=%s,catch=%s)"),
966                 reform(send,0),reform(term,1),reform(catch,2));
967         if (!(osend=send)) send="";
968         if ((catch_any=(catch && !strcmp(catch,"@")))) catch=NULL;
969         if ((errout=(*send=='!'))) send++;
970         errout|=(maxretryn==-1);
971         if ((extend=(*send=='~'))) send++;
972         alarmtime=readtimen*(extend?EXT_READTIME:1);
973         buf[bufl]='\0'; /* for d8() below */
974         d8("devcmd(), alarmtime=%ld, errout=%d, extend=%d, catch_any=%d, osend=%p, bufl=%d, buf: %s\n",
975                 alarmtime,errout,extend,catch_any,osend,bufl,reform(buf,0));
976         assert(!catch || !strchr(catch,'\r')); /* we are no longer supporting 'noconvcr'! */
977         assert(!term  || !strchr(term ,'\r'));
978         if (0) {
979 err:
980                 alarm(0);
981                 if (errout) return(NULL);
982                 retrying();
983                 }
984         catchdatal=0;
985         if (osend) {
986                 bufl=0;
987                 d1("Resetting bufl.\n");
988                 va_start(ap,send);
989                 l=VARVPRINTF(buf,send,ap); bufl=l+(!!osend);
990                 va_end(ap);
991                 if (bufl>=sizeof(buf)-1) error(_("!Command too big (%d>%d)"),bufl,sizeof(buf)-1);
992                 if (verbose>=2) error(_(".devcmd formatted send=%s%s"),reform(buf,0),(osend?"+\"\\r\"":""));
993                 if (osend) buf[l]='\r';
994                 for (offs=0,got=0;offs<bufl;offs++) {
995                         alarm(MAXSENDTIME);
996                         usleep((offs?chartimen:cmdtimen)*1000);
997                         if (!offs && tcflush(devfd,TCIOFLUSH))
998                                 error(_("^Error flushing I/O queue of device"));
999                         if (write(devfd,buf+offs,1)!=1) break;
1000                         got++;
1001                         if (tcdrain(devfd))
1002                                 error(_("^Error forcing output of char at pos %d of cmd %s"),offs,reform(buf,0));
1003                         }
1004                 alarm(0);
1005                 if (got!=bufl) {
1006                         error(_("^Wrote only %d of %d bytes of command"),got,bufl);
1007                         goto err;
1008                         }
1009                 }
1010
1011         if (!(terml=strlen(term))) {
1012                 assert(!catch); assert(!catch_any);
1013                 return(NULL);
1014                 }
1015         if (catch) {
1016                 catchl=strlen(catch);
1017                 fragl=MAX(terml,catchl);
1018                 }
1019         else fragl=terml;
1020         fragl=MAX(fragl,MAX(strlen(ERROR_SUBSTR1),strlen(ERROR_SUBSTR2)));
1021         record=recordend=NULL;
1022         wasalarm=0;
1023         alarm(alarmtime);
1024         edata='\n';
1025         if (!osend) {
1026                 /* "bufl" important */
1027                 goto skipread;
1028                 }
1029         for (;;) {
1030                 blocking(0);
1031                 errno=0;
1032                 got=read(devfd,buf+bufl,sizeof(buf)-1-bufl);
1033                 if (got==-1 && errno==EAGAIN) {
1034                         blocking(1);
1035                         errno=0;
1036                         got=read(devfd,buf+bufl,1);
1037                         }
1038                 if (got<=0) {
1039                         buf[bufl]='\0'; /* for strspn() below */
1040                         if (!strcmp(term,"\n") && catch /* written to trap on 'devcmd("\n","+CMT:"," ")' */
1041                             && bufl==strspn(buf,"\n" /* accept */)) { /* only newlines found */
1042                                 if (verbose>=2)
1043                                         error(_(".Blank (%d newlines) input read, ignoring it"),bufl);
1044                                 bufl=0; /* discard newlines */
1045                                 return(&devcmd_empty_return);
1046                                 }
1047                         if (wasalarm) error(_("Maximum response timeout (%lds) exceeded"),alarmtime);
1048                         else error(_("^Couldn't read device data (ret=%d)"),got);
1049                         goto err;
1050                         }
1051                 bufl2=bufl+got;
1052                 buf[bufl2]='\0';
1053                 s=buf+bufl;
1054                 while (buf+bufl2>s && (s=memchr(s,'\0',buf+bufl2-s))) *s++=REPL_NULLCHAR;
1055                 if (verbose>=3)
1056                         error(_("\nGot chunk of data from device: %s"),reform(buf+bufl,0));
1057                 /* convert CR */ {
1058                         s=buf+bufl;
1059                         while (buf+bufl2>s && (s=memchr(s,'\r',buf+bufl2-s))) *s++='\n';
1060                         }
1061                 bufl=bufl2;
1062 skipread:
1063                 catched(buf+bufl,edata); assert(!record || record==buf+bufl);
1064                 assert(bufl<sizeof(buf)-1);
1065                 buf[bufl]='\0';
1066                 assert(strlen(buf)==bufl);
1067                 /* d3(">%s|%s<\n",buf,term); */
1068                 if (strstr(buf,ERROR_SUBSTR1) || strstr(buf,ERROR_SUBSTR2)) {
1069                         error(_("Found ERROR response on command %s"),reform(send,0));
1070                         goto err;
1071                         }
1072 /* "record" may get NULLed here after successful 'catch'
1073  * but "recordend" will never be NULLed
1074  */
1075                 if (catch && !recordend && bufl>=catchl && (hit=strstr(buf,catch))) {
1076                         record=hit+catchl;
1077                         catched(buf+bufl,edata); assert(!record || record==buf+bufl);
1078                         }
1079                 if (catch_any && !recordend && buf[discard=strspn(buf,"\n" /* accept */)]) {
1080                         record=buf+discard;
1081                         catched(buf+bufl,edata); assert(!record || record==buf+bufl);
1082                         }
1083                 if (((!catch && !catch_any) || catchdatal) && bufl>= terml
1084                     && (hit=strstr((recordend?recordend:buf),term))) {
1085                         memmove(buf,hit+terml,(bufl2=(buf+bufl)-(hit+terml))); bufl=bufl2;
1086                         break;
1087                         }
1088                 if (bufl<fragl) continue;
1089                 memmove(buf,buf+bufl-(fragl-1),(bufl2=fragl-1));
1090                 if (record   ) record-=bufl-bufl2;
1091                 if (recordend) recordend-=bufl-bufl2;
1092                 bufl=bufl2;
1093                 }
1094         alarm(0);
1095         if (!catchdatal) {
1096                 assert(!catch && !catch_any);
1097                 return("");
1098                 }
1099         assert(!!catch || catch_any);
1100         record=emptystring;
1101         catched(record+1,edata);
1102         if (verbose>=2) error(_(".Returning data %s for cmd %s"),reform(catchdata,0),reform(send,1));
1103         return(catchdata);
1104 }
1105
1106 static int prepaddr(unsigned char *d,const char *addr)
1107 {
1108 int tot=0;
1109 char flip=0,plus;
1110 unsigned char n;
1111
1112         if ((plus=(*addr=='+'))) addr++;
1113         *++d=(plus?ADDR_INT:ADDR_NAT);
1114         while (*addr) {
1115                 if (*addr<'0' || *addr>'9')
1116                         error(_("!Error during conversion of number at: %s"),addr);
1117                 tot++;
1118                 n=(*addr++)-'0';
1119                 if ((flip=!flip)) *++d=0xF0|n;
1120                 else *d=(*d&0x0F)|(n<<4U);
1121                 }
1122         return(tot);
1123 }
1124
1125 static char *finalsmsc;
1126 #define SMSCBINSIZE (1+1+(MAXNUMLEN+1)/2)
1127 static char pdusmsc[SMSCBINSIZE*2+1];
1128
1129 static inline char tohex(unsigned char x)
1130 {
1131         x&=0x0F;
1132         if (x<10) return(x   +'0');
1133                   return(x-10+'A');
1134 }
1135
1136 static inline void textconv(char *d,unsigned char *s,size_t len)
1137 {
1138         while (len--) {
1139                 *d++=tohex(*s>>4U);
1140                 *d++=tohex(*s    );
1141                 s++;
1142                 }
1143         *d='\0';
1144 }
1145
1146 static inline void smscset(void)
1147 {
1148 char *s,*t,*e,*serr;
1149 unsigned char bin[2+(MAXNUMLEN+1)/2];
1150
1151         if (smsc) devcmd(NULL,NULL,"\r\nAT+CSCA=\"%s\"",smsc);
1152         s=devcmd(NULL,"\n+CSCA:","\r\nAT+CSCA?");
1153         while (isspace(*s)) s++;
1154         if (!*s || !strcmp(s,"EMPTY"))
1155                 error(_("!No SMSC set in mobile station found, please use option \"-s\""));
1156         if (verbose>=1) error(_("\nFound default SMSC in mobile: %s"),s);
1157         if (*s++!='"') error(_("!No left-quote found in: %s"),s);
1158         if (!(t=strrchr(s,'"'))) error(_("!No right-quote found in: %s"),s);
1159         if (s==t)
1160                 error(_("!No SMS set in mobile station found, please use option \"-s\""));
1161         e=t++;
1162         while (isspace(*t)) t++;
1163         if (*t) {
1164 long l;
1165
1166                 if (*t++!=',') error(_("!No comma found after quotes in: %s"),s);
1167                 while (isspace(*t)) t++;
1168                 l=strtol(t,&serr,10);
1169                 if ((l!=ADDR_NAT && l!=ADDR_INT) || (serr && *serr))
1170                         error(_("!Type parse error in: %s"),s);
1171                 if (l==ADDR_INT && *s!='+') *--s='+';
1172                 }
1173         *e='\0';
1174         if (verbose>=2) error(_("\nDecoded SMSC address: %s"),s);
1175         if (!NEED_PDUSMSC()) return;
1176         chk(finalsmsc=strdup(s));
1177         bin[0]=1+(prepaddr(bin,finalsmsc)+1)/2;
1178         textconv(pdusmsc,bin,bin[0]+1);
1179 }
1180
1181 static inline unsigned char charconv_send(char c,size_t offs)
1182 {
1183         switch (c) {
1184                 case '@': return(0);
1185                 case '$': return(2);
1186                 case 0: assert(0);
1187                 default:
1188                         return(c&0x7F);
1189                 }
1190 #if 0
1191         if ((c>='A' && c<='Z') || (c>='a' && c<='z') || (c>='0' && c<='9')) return(c);
1192         error(_("Can't convert character '%c' (0x%02X) at offs %d (0-based), substituted '?'"),
1193                 c,(unsigned char)c,offs);
1194         return('?');
1195 #endif
1196 }
1197
1198 static inline unsigned char charconv_recv(char c,size_t offs)
1199 { /* FIXME: unify with charconv_send() */
1200         switch (c) {
1201                 case 0: return('@');
1202                 case 2: return('$');
1203                 default:
1204                         return(c);
1205                 }
1206 /* strict checking not done, see charconv_send */
1207 }
1208
1209 /* Logo format shamelessly stolen from GNokii-0.3.0: http://www.gnokii.org/
1210  * Beware - Nokia Smart Messaging specification 1.0.0 and 2.0.0 is incompatible
1211  * with Nokia current product line implementation
1212  * http://www.forum.nokia.com/developers/smartmsg/download/ssm2_0_0.pdf
1213  */
1214
1215 static char *pdudata;
1216 static struct hexdata {
1217         struct hexdata *next;
1218         char data[140*2+1];
1219         } *hexdata,**hexdatatail=&hexdata;
1220
1221 static void nokiaprep(unsigned char *bin,size_t w)
1222 {
1223 struct hexdata *hd;
1224         assert(w<=140);
1225         chk(hd=malloc(sizeof(*hd)));
1226         *hexdatatail=hd;
1227         hd->next=NULL;
1228         hexdatatail=&hd->next;
1229         textconv(hd->data,bin,w);
1230         if (verbose>=2) error(_("\nWill send hexdata: %s"),hd->data);
1231 }
1232
1233 static inline void logoread(void)
1234 {
1235 FILE *f;
1236 char buf[32+140*8+1];
1237 unsigned char bin[140]={
1238         0x06, /* UDH length */
1239         0x05, /* IEI */
1240         0x04, /* IEDL */
1241         0x15, 0x83, /* dest port (group gfx) */
1242         0x00, 0x00  /* src port (unused) */
1243         };
1244 size_t got,r=0 /* GCC happiness */,w;
1245 ssize_t chars,bits;
1246 char gsmnetf[10];
1247 int sizex,sizey,bit;
1248
1249 #define WORD(n) (((unsigned char)buf[(n)])|(((unsigned char)buf[(n)+1])<<8))
1250
1251         if (!(f=fopen(logoname,"rb")))
1252                 error(_("^!Cannot open logo file \"%s\" for r/o"),logoname);
1253         got=fread(buf,1,sizeof(buf),f);
1254         chkfclose(f,logoname);
1255              if (got>=20 && !memcmp(buf,"NOL",4)) {
1256                 VARPRINTF2(gsmnetf,"%03.3u%02.2u",WORD(6),WORD(8));
1257                 assert(strlen(gsmnetf)==5);
1258                 r=10;
1259                 if (verbose>=1) error(_(".Reading NOL file \"%s\", GSMnet \"%s\", word@4=%d.."),
1260                         logoname,gsmnetf,WORD(4));
1261                 }
1262         else if (got>=16 && !memcmp(buf,"NGG",4)) {
1263                 r=6;
1264                 if (verbose>=1) error(_(".Reading NGG file \"%s\", word@4=%d.."),
1265                         logoname,WORD(4));
1266                 }
1267         else error(_("!Unknown file format of logo file \"%s\""),logoname);
1268         if (gsmnet && !strtrycasecmp(gsmnet,WORD_NET)) {
1269                 if (!*gsmnetf) error(_("!NOL network code detection requested but NOL file not loaded, please specify network code"));
1270                 gsmnet=gsmnetf;
1271                 }
1272         if (!gsmnet || !strtrycasecmp(gsmnet,WORD_GROUP) || !*gsmnet) {
1273                 error(_("\nSending logo as: group graphics"));
1274                 gsmnet=NULL;
1275                 }
1276         else {
1277                 error(_("\nSending logo as: operator logo for \"%s\""),gsmnet);
1278                 bin[4]=0x82; /* dest port 0x1582 */
1279                 }
1280         
1281         sizex=WORD(r); sizey=WORD(r+2);
1282         if (verbose>=2) error(_(".Magic words: @+4=%d, @+6=%d, @+8=%d"),
1283                         WORD(r+4),WORD(r+6),WORD(r+8));
1284         r+=10;
1285         if (sizex<1 || sizex>255
1286          || sizey<1 || sizey>255) error(_("!Invalid size: %dx%d"),sizex,sizey);
1287         chars=((bits=sizex*sizey)+7)/8;
1288         if (r+bits>got) error(_("!Logo file \"%s\" too short - actual=%d, need(%dx%d)=%d"),
1289                 logoname,got,sizex,sizey,r+chars);
1290         else if (r+bits<got)
1291                 if (verbose>=1) error(_("Ignoring trailing garbage in \"%s\", used only %d bytes"),logoname,r+bits);
1292         if ((got=(7+(gsmnet?3:0)+4+chars))>140)
1293                 error(_("!SMS size would be %d bytes but 140 is maximum"),got);
1294         w=7;
1295         if (gsmnet) {
1296                 bin[w++]=((gsmnet[1]&0x0F)<<4)|(gsmnet[0]&0x0F);
1297                 bin[w++]=0xF0                 |(gsmnet[2]&0x0F);
1298                 bin[w++]=((gsmnet[4]&0x0F)<<4)|(gsmnet[3]&0x0F);
1299                 }
1300         bin[w++]=0x00; /* RFU by Nokia */
1301         bin[w++]=sizex; bin[w++]=sizey;
1302         bin[w++]=0x01; /* one B/W plane */
1303         while (chars--) {
1304                 bin[w]=0;
1305                 for (bit=0x80;(bits>0) && (bit>0);bits--,bit>>=1) {
1306                         if (buf[r]!='0' && buf[r]!='1')
1307                                 error(_("!Invalid character (neither '0' nor '1') in logo file \"%s\" at offset 0x%X"),
1308                                         logoname,r);
1309                         if (buf[r++]=='1') bin[w]|=bit;
1310                         }
1311                 w++;
1312                 }
1313         assert(chars==-1); assert(bits==0); assert(w==got);
1314         nokiaprep(bin,w);
1315 #undef WORD
1316 }
1317
1318 static inline void ringread(void)
1319 {
1320 FILE *f;
1321 unsigned char bin1[140]={
1322         6, /* UDH length */
1323         0x05, /* IEI */
1324         0x04, /* IEDL */
1325         0x15, 0x81, /* dest port (ring tones) */
1326         0x15, 0x81  /* src port (unused) */
1327 #define BIN1_PAYLOAD (140-7)
1328         };
1329 unsigned char binn[140]={
1330         11, /* UDH length */
1331         0x05, /* IEI */
1332         0x04, /* IEDL */
1333         0x15, 0x81, /* dest port (ring tones) */
1334         0x15, 0x81, /* src port (unused) */
1335         0x00, 0x03, /* multipart */
1336         /* 0x??, unique serial ID */
1337         /* 0x??, total messages */
1338         /* 0x??, message number (# from 1) */
1339 #define BINN_PAYLOAD (140-12)
1340         };
1341 size_t got,want;
1342 int totn,fragn;
1343 long size;
1344
1345 #define WORD(n) (((unsigned char)buf[(n)])|(((unsigned char)buf[(n)+1])<<8))
1346
1347         if (!(f=fopen(ringname,"rb")))
1348                 error(_("^!Cannot open ring file \"%s\" for r/o"),ringname);
1349         if ((size=getfilesize(f,ringname))==-1)
1350                 error(_("!File size determination is essential to continue operation"));
1351         if (size<0x103)
1352                 error(_("!File \"%s\" size %ld too small (must >=0x103)! Is it .000 file?"),
1353                         ringname,size);
1354         if (fseek(f,0x100,SEEK_SET))
1355                 error(_("^Seeking error on \"%s\", ignoring"),ringname);
1356         size-=0x100;
1357         if (size<=BIN1_PAYLOAD) {
1358                 if ((got=fread(bin1+7,1,size,f))!=size)
1359                         error(_("^Read error on \"%s\", wanted %ld, got %d"),ringname,size,got);
1360                 error(_("\nSending ring tone \"%s\" as single SMS (size %ld, max %d)"),
1361                         ringname,size,BIN1_PAYLOAD);
1362                 nokiaprep(bin1,7+size);
1363                 }
1364         else {
1365                 totn=(size+BINN_PAYLOAD-1)/BINN_PAYLOAD;
1366                 if (totn>0xFF)
1367                         error(_("!File size %ld too large even for multi-SMS ring upload (max=%d)"),
1368                                 size,BINN_PAYLOAD*0xFF);
1369                 binn[10]=totn;
1370                 if (verbose>=1)
1371                         error(_("\nSending ring tone \"%s\" as %d multi-SMSes (size %ld, max %d, frag %d)"),
1372                                 ringname,totn,size,BIN1_PAYLOAD,BINN_PAYLOAD);
1373                 binn[9]=time(NULL)&0x100; /* rand() would be better but it is a compatibility pain */
1374                 if (verbose>=1)
1375                         error(_("\nUsing unique multi-SMS ID 0x%02X"),(unsigned)binn[9]);
1376                 for (fragn=1;fragn<=totn;fragn++) {
1377                         binn[11]=fragn;
1378                         want=MIN(size,BINN_PAYLOAD);
1379                         if ((got=fread(binn+12,1,want,f))!=want)
1380                                 error(_("^Read error on \"%s\", wanted %d, got %d"),ringname,want,got);
1381                         nokiaprep(binn,12+want);
1382                         size-=want;
1383                         }
1384                 }
1385         chkfclose(f,ringname);
1386 #undef WORD
1387 }
1388
1389 static inline void genpdu(void)
1390 {
1391 static unsigned char pdu[64+MAXNUMLEN/2+(MAXBODYLEN*7)/8];
1392 unsigned char *d=pdu;
1393 int i;
1394 char inb=0,outb=0,xb,*bodyr;
1395 unsigned char inreg=0 /* GCC happiness */;
1396 size_t offs=0;
1397
1398         *d++=PDU_TYPE;
1399         *d++=PDU_MR;
1400         i=prepaddr(d,phone);
1401         *d=i; d+=1+1+(i+1)/2;
1402         *d++=PDU_PID;
1403         *d++=PDU_DCS;
1404         *d++=PDU_VP;
1405         if (bodylen>MAXBODYLEN) {
1406                 error(_("Body too large (%d>%d), cut"),bodylen,MAXBODYLEN);
1407                 body[(bodylen=MAXBODYLEN)]='\0';
1408                 }
1409         bodyr=body;
1410         *d=bodylen;
1411         assert(d<pdu+sizeof(pdu));
1412         while (bodylen || inb) {
1413                 if (!inb) {
1414                         assert(bodylen>0); assert(!!*body);
1415                         inreg=charconv_send(*bodyr++,offs++);
1416                         bodylen--;
1417                         inb=7;
1418                         }
1419                 if (!outb) {
1420                         *++d=0x00;
1421                         outb=8;
1422                         }
1423                 xb=MIN(inb,outb);
1424 #if 0
1425                 d4("inb=%d,outb=%d,xb=%d\n",inb,outb,xb);
1426 #endif
1427                 *d|=((inreg>>(unsigned)(7-inb))&((1<<xb)-1))<<(unsigned)(8-outb);
1428                 inb-=xb; outb-=xb;
1429                 }
1430         d++;
1431         assert(d<pdu+sizeof(pdu));
1432         pdudata=malloc(2*(d-pdu)+1);
1433         textconv(pdudata,pdu,d-pdu);
1434 }
1435
1436 static inline void preparebody(void)
1437 {
1438 FILE *fin=NULL /* GCC happiness */;
1439 char *finame;
1440
1441         if (body && readbody) {
1442                 finame=body;
1443                 body=NULL;
1444                 }
1445         else {
1446                 finame=NULL;
1447                 fin=stdin;
1448                 }
1449         if (body) return;
1450         readbody=0;
1451         if (!finame) {
1452                 if (verbose>=1)
1453                         error(_("\nPlease enter the SMS text body, end with EOF (ctrl-D):"));
1454                 }
1455         else {
1456                 if (!(fin=fopen(finame,"rt")))
1457                         error(_("^!Can't open data file \"%s\" for r/o"),finame);
1458                 }
1459         chk(body=malloc(BODYLOAD));
1460         bodylen=fread(body,1,BODYLOAD,fin);
1461         if (bodylen==-1)
1462                 error(_("^!Error reading stream \"%s\""),(finame?finame:_("<stdin>")));
1463         if (finame) {
1464                 chkfclose(fin,finame);
1465                 free(finame);
1466                 }
1467 }
1468
1469 static int datawait(char immed)
1470 {
1471 int i;
1472 #ifdef HAVE_POLL
1473 struct pollfd ufd;
1474 #else /* HAVE_POLL */
1475 fd_set rfds,xfds;
1476 #endif /* HAVE_POLL */
1477
1478         assert(devfd>=0);
1479 retry:
1480         if (!immed && verbose>=2)
1481                 error(_(".Waiting for device incoming data.."));
1482 #ifdef HAVE_POLL
1483         ufd.fd=devfd;
1484         ufd.events=POLLIN;
1485         ufd.revents=0;
1486         errno=0;
1487         i=poll(&ufd,1,(immed?0:-1));
1488 #else /* HAVE_POLL */
1489 #ifdef HAVE_FD_SETSIZE
1490         if (devfd>=FD_SETSIZE)
1491                 error(_("!Device file descriptor %d can't fit in select() FD_SETSIZE (%d)"),
1492                         devfd,FD_SETSIZE);
1493 #endif /* HAVE_FD_SETSIZE */
1494         FD_ZERO(&rfds); FD_SET(devfd,&rfds);
1495         FD_ZERO(&xfds); FD_SET(devfd,&xfds);
1496         errno=0;
1497         i=select(devfd+1,&rfds,NULL,&xfds,NULL);
1498 #endif /* HAVE_POLL */
1499         if (immed && i==0) return(0);
1500         if (i==-1 && errno==EINTR)
1501                 goto retry; /* silent retry, for example SIGCHLD could occur */
1502         if (i!=1)
1503                 error(_("^Failed (retval %d) while waiting for data, ignoring"),i);
1504
1505 #ifdef HAVE_POLL
1506         if (ufd.revents&(POLLERR|POLLHUP))
1507 #else /* HAVE_POLL */
1508         if (FD_ISSET(devfd,&xfds))
1509 #endif /* HAVE_POLL */
1510                 error(_("^Error while waiting for data, ignoring"));
1511
1512 #ifdef HAVE_POLL
1513         if (!(ufd.revents&POLLIN))
1514 #else /* HAVE_POLL */
1515         if (!(FD_ISSET(devfd,&rfds)))
1516 #endif /* HAVE_POLL */
1517                 {
1518                 error(_("^No data input after waited for data, retrying"));
1519                 goto retry;
1520                 }
1521         return(1);
1522 }
1523
1524 static char *check_format(const char *fmt,const char *string)
1525 {
1526 static char err[LINE_MAX],sub[50];
1527 char cf,cs;
1528 const char *sf,*ss,*subp;
1529
1530         for (sf=fmt,ss=string;(cf=*sf) && (cs=*ss);sf++,ss++) {
1531                 subp=NULL;
1532                 switch (cf) {
1533                         case '?':
1534                                 break;
1535                         case '9':
1536                                 if (isdigit(cs)) break;
1537                                 subp=_("digit");
1538                                 break;
1539                         case '+':
1540                                 if (cs=='+' || cs=='-') break;
1541                                 subp=_("+/- sign");
1542                                 break;
1543                         default:
1544                                 if (cf==cs) break;
1545                                 VARPRINTF(sub,"'%c'",cf); subp=sub;
1546                         }
1547                 if (!subp) continue;
1548                 VARPRINTF5(err,_("Expected %s, found '%c' at pos %d of string [%s], formatstring [%s]"),
1549                         subp,cs,ss-string,string,fmt);
1550                 return(err);
1551                 }
1552         if (*sf) {
1553                 VARPRINTF2(err,_("String too short for format, string [%s], formatstring [%s]"),
1554                         string,fmt);
1555                 return(err);
1556                 }
1557         if (*ss) {
1558                 VARPRINTF2(err,_("Trailing garbage in string [%s], formatstring [%s]"),
1559                         string,fmt);
1560                 return(err);
1561                 }
1562         return(NULL);
1563 }
1564
1565 static char *receive_number,*receive_smsc;
1566 static time_t receive_time;
1567
1568 struct tm tm;
1569 static const struct {
1570         off_t strpos;
1571         off_t tmpos;
1572         int min,max;
1573         const char *name;
1574         } timeparse[]={
1575 #define TP_ENT(a,b,c,d,e) { a,offsetof(struct tm,b),c,d,e }
1576                 TP_ENT( 3,tm_year,0,99,N_("year")),
1577                 TP_ENT( 6,tm_mon ,1,12,N_("month")),
1578                 TP_ENT( 9,tm_mday,1,31,N_("day of month")),
1579                 TP_ENT(12,tm_hour,0,23,N_("hour")),
1580                 TP_ENT(15,tm_min ,0,59,N_("minute")),
1581                 TP_ENT(18,tm_sec ,0,59,N_("second")),
1582                 /* Time zone ignored */
1583                 };
1584 #define GETTIME(i) (*(int *)(((char *)&tm)+timeparse[(i)].tmpos))
1585
1586 static void maketime(const char *string)
1587 {
1588 int val;
1589 int i;
1590
1591         for (i=0;i<NELEM(timeparse);i++) {
1592                 val=GETTIME(i);
1593                 if (val<timeparse[i].min || val>timeparse[i].max) {
1594                         error(_("Weird value of %s, is %d but expected %d..%d, setting to %d"),
1595                                 _(timeparse[i].name),val,timeparse[i].min,timeparse[i].max,timeparse[i].min);
1596                         GETTIME(i)=timeparse[i].min;
1597                         }
1598                 }
1599         if (tm.tm_year<70) tm.tm_year+=100;
1600         tm.tm_mon--;
1601         d7("mktime(y%dm%dd%dh%dm%ds%d)\n",
1602                 tm.tm_year,tm.tm_mon,tm.tm_mday,tm.tm_hour,tm.tm_min,tm.tm_sec);
1603         tm.tm_isdst=-1; /* "timezone" info not available */
1604         if ((receive_time=mktime(&tm))==-1)
1605                 error(_("^mktime(3) failed for %s"),string);
1606 }
1607
1608 /* +CMT: "+420602431329",,"99/10/25,03:21:03-00" */
1609 static int receive_headerparse(char *buf)
1610 {
1611 char *s,*s1,*err;
1612 int i;
1613
1614 #define DIGIT2ASC(s) (((s)[0]-'0')*10+((s)[1]-'0'))
1615
1616         for (s=buf;*s==' ';s++);
1617         if (*s++!='"') {
1618                 error(_("Cannot find initial '\"' in CMT header: %s"),buf);
1619                 return(0);
1620                 }
1621         for (s1=s;*s && *s!='"';s++);
1622         if (!*s) {
1623                 error(_("Only one '\"' found in CMT header: %s"),buf);
1624                 return(0);
1625                 }
1626         free(receive_smsc); receive_smsc=NULL;
1627         free(receive_number);
1628         chk(receive_number=malloc(s-s1+1));
1629         memcpy(receive_number,s1,s-s1); receive_number[s-s1]='\0';
1630         s++;
1631         if ((err=check_phone(receive_number)) ||
1632             (err=check_format(",,\"99/99/99,99:99:99+99\"",s))) {
1633                 error(_("%s in CMT header: %s"),err,buf);
1634                 return(0);
1635                 }
1636         memset(&tm,0,sizeof(tm)); /* may be redundant */
1637         for (i=0;i<NELEM(timeparse);i++)
1638                 GETTIME(i)=DIGIT2ASC(s+timeparse[i].strpos);
1639         maketime(s+2);
1640         return(1);
1641 #undef DIGIT2ASC
1642 }
1643
1644 static void signal_chld(int signo)
1645 {
1646 int status;
1647 pid_t pid;
1648
1649         signal(SIGCHLD,(RETSIGTYPE (*)(int))signal_chld);
1650         /* we don't care about siginterrupt(3) as it doesn't matter how it is set */
1651
1652         d2("signal_chld: signo=%d\n",signo);
1653         while (0<(pid=waitpid(-1 /* ANY process */,&status,WNOHANG /* options */))) {
1654                 if (verbose>=2)
1655                         error(_(".Child process w/PID %d has exited, %s, status=%d"),
1656                                         pid,(WIFEXITED(status)? _("normally") : _("abnormally")),(WIFEXITED(status) ? WEXITSTATUS(status) : -1));
1657                 }
1658 }
1659
1660 static void receive_text(char *bodyline)
1661 {
1662 char *buf,*s,*s1,*s2,*s3;
1663 pid_t pid;
1664 char tbuf[32];
1665 int i;
1666 FILE *f;
1667
1668         d2("receive_text: %s\n",bodyline);
1669         signal(SIGCHLD,(RETSIGTYPE (*)(int))signal_chld);
1670 #if RECEIVE_TEST
1671         pid=0;
1672 #else
1673         pid=fork();
1674 #endif
1675         if (pid>0) {
1676                 if (verbose>=2)
1677                         error(_(".Spawned child receive-SMS process w/PID %d"),pid);
1678                 return; /* parent context */
1679                 }
1680         if (pid==-1) {
1681                 error(_("Can't fork(2), process spawning may block receive"));
1682                 }
1683         else { /* child process */
1684                 dis_cleanup=1;
1685                 }
1686         for (s=body;*s;) {
1687                 s1=s;
1688                 do {
1689                         s1=strchr(s1+(s1!=s),'%');
1690                         } while (s1 && s1[1]!='p' && s1[1]!='T' && s1[1]!='t' && s1[1]!='s');
1691                 if (!s1) {
1692                         pushargstack_one(s,0);
1693                         break;
1694                         }
1695                 *s1='\0';
1696                 pushargstack_one(s,0);
1697                 *s1++='%';
1698                 s=s1;
1699                 switch (*s++) {
1700                         case 'p':
1701                                 pushargstack_one(receive_number,0);
1702                                 break;
1703                         case 'T':
1704                                 VARPRINTF(tbuf,"%ld",receive_time);
1705                                 pushargstack_one(tbuf,0);
1706                                 break;
1707                         case 't':
1708                                 if (receive_time==-1) break;
1709                                 if (!(s2=ctime(&receive_time))) {
1710                                         error(_("Failing ctime(3), ignoring substitution"));
1711                                         break;
1712                                         }
1713                                 if ((s3=strchr(s2,'\n'))) *s3='\0';
1714                                 pushargstack_one(s2,0);
1715                                 break;
1716                         case 's':
1717                                 if (receive_smsc) pushargstack_one(receive_smsc,0);
1718                                 break;
1719                         default: assert(0);
1720                         }
1721                 }
1722         buf=glueargstack(NULL,NULL); assert(buf);
1723         if (!(f=popen(buf,"w"))) {
1724                 error(_("^Failing spawn of receive command: %s"),buf);
1725                 goto err;
1726                 }
1727         if (fputs(bodyline,f)<0 || putc('\n',f)!='\n')
1728                 error(_("^Failing write to child receive command: %s"),buf);
1729         if ((i=pclose(f)))
1730                 error(_("^Spawned receive command failure (code %d): %s"),i,buf);
1731 err:
1732         free(buf);
1733         if (pid==-1) return;
1734         exit(EXIT_SUCCESS); /* cleanup() has been disabled */
1735 }
1736
1737 static inline unsigned char fromhex(unsigned c)
1738 {
1739         c&=0xDF;
1740         return(c<'A'?c-('0'&0xDF):(c-('A'&0xDF))+0xA);
1741 }
1742
1743 static int teldecode(char *text,unsigned char *bin,size_t digits)
1744 {
1745 unsigned char b;
1746 int r=0,i;
1747
1748         for (i=0;i<digits;text++,i++) {
1749                 if (!(i&1)) b=*bin;
1750                 else b=(*bin++)>>4;
1751                 b&=0x0F;
1752                 if (b<=0x09)
1753                         *text=b+'0';
1754                 else {
1755                         *text='?';
1756                         r++;
1757                         }
1758                 }
1759         *text='\0';
1760         return(r);
1761 }
1762
1763 static void sctsparse(unsigned char *bin,const char *pduline,int offs)
1764 {
1765 #define DIGIT2BIN(v) (((v)&0x0F)*10+(((v)>>4)&0x0F))
1766 int i;
1767
1768         receive_time=-1;
1769         memset(&tm,0,sizeof(tm)); /* may be redundant */
1770         for (i=0;i<NELEM(timeparse);offs++,i++) {
1771                 if ((*bin&0x0F)>0x09 || (*bin&0xF0)>0x90) {
1772                         error(_("Invalid value of \"%s\" at offset %d in: %s"),
1773                                 timeparse[i].name,offs,pduline);
1774                         return;
1775                         }
1776                 GETTIME(i)=DIGIT2BIN(*bin);
1777                 bin++;
1778                 }
1779         maketime(pduline);
1780
1781 #undef DIGIT2BIN
1782 }
1783
1784 static void receive_pdu(char *pduline)
1785 {
1786 unsigned char pdu[140+0x100],*pdup,*pdue,oalen,inreg;
1787 char text[160+1],*textp,*s,*pdulinescan;
1788 size_t pdulinel=strlen(pduline),want;
1789 size_t udl,udlb;
1790 int inb,outb,xb;
1791
1792         d2("receive_pdu: %s\n",pduline);
1793         if (pdulinel>2*sizeof(pdu))
1794                 { error(_("PDU too long (%d/2) to be valid: %s"),pdulinel,pduline); return; }
1795         if (pdulinel&1)
1796                 { error(_("PDU length odd (%d): %s"),pdulinel,pduline); return; }
1797         if (pdulinel<2*13)
1798                 { error(_("PDU length %d too small (min. 2*%d): %s"),pdulinel,13,pduline); return; }
1799         for (pdup=pdu,pdulinescan=pduline;*pdulinescan;pdulinescan+=2) {
1800                 if (!isxdigit(pdulinescan[0]) || !(isxdigit(pdulinescan[1])))
1801                 { error(_("Invalid hex byte: %c%c on byte %d in: %s"),
1802                         pdulinescan[0],pdulinescan[1],pdup-pdu,pduline); return; }
1803                 *pdup++=(fromhex(pdulinescan[0])<<4)|fromhex(pdulinescan[1]);
1804                 }
1805         pdue=pdup;
1806         free(receive_smsc);
1807         if (*pdu<=1) {
1808                 receive_smsc=NULL;
1809                 }
1810         else {
1811                 if (*pdu>10)
1812                         { error(_("SMSC length too large (%d, max. %d): %s"),*pdu,10,pduline); return; }
1813                 chk(receive_smsc=malloc(1+2*(*pdu)+1));
1814                 s=receive_smsc;
1815                 if (pdu[1]==ADDR_INT) *s++='+';
1816                 else {
1817                         if (pdu[1]!=ADDR_NAT)
1818                                 error(_("Unknown address type 0x%02X of %s, ignoring in PDU: %s"),pdu[1],_("SMSC"),pduline); return;
1819                         }
1820                 if (teldecode(s,pdu+2,2*(*pdu-1)-((pdu[1+(*pdu)]&0xF0)==0xF0)))
1821                         error(_("Some digits unrecognized in %s \"%s\", ignoring in PDU: %s"),_("SMSC"),receive_smsc,pduline);
1822                 }
1823         pdup=pdu+1+(*pdu);
1824         if (*pdup&0x03) /* PDU type */
1825                 error(_("Unrecognized PDU type 0x%02X at offset %d, dropping: %s"),*pdup,pdup-pdu,pduline);
1826         pdup++;
1827         free(receive_number);
1828         if ((oalen=*pdup++)>2*0x10) /* OA len */
1829                 { error(_("Originating number too large (0x%X, max. 2*0x%X): %s"),oalen,0x10,pduline); return; }
1830         if (pdup+(want=1+(oalen+1)/2+10)>pdue)
1831                 { error(_("PDU length too short (want %d, is %d): %s"),(pdup-pdu)+want,pdue-pdu,pduline); return; }
1832         chk(receive_number=malloc(1+2*(*pdup)+1));
1833         s=receive_number;
1834         if (*pdup==ADDR_INT) *s++='+';
1835         else {
1836                 if (*pdup!=ADDR_NAT)
1837                         error(_("Unknown address type 0x%02X of %s, ignoring in PDU: %s"),*pdup,_("originating number"),pduline); return;
1838                 }
1839         pdup++;
1840         if (teldecode(s,pdup,oalen))
1841                 error(_("Some digits unrecognized in %s \"%s\", ignoring in PDU at offset %d: %s"),
1842                         _("originating number"),receive_number,pdup-pdu,pduline);
1843         pdup+=(oalen+1)/2;
1844         if (*pdup) /* PID */
1845                 error(_("PID number %02X unsupported, ignoring: %s"),*pdup,pduline);
1846         pdup++;
1847         if (*pdup) { /* DCS */
1848                 if ((*pdup&0xF4)==0xF4)
1849                         { error(_("DCS 0x%02X indicates 8-bit data, unsupported, dropping: %s"),*pdup,pduline); return; }
1850                 error(_("DCS 0x%02X unsupported, will attempt decoding: %s"),*pdup,pduline);
1851                 }
1852         pdup++;
1853         sctsparse(pdup,pduline,pdup-pdu);
1854         pdup+=7;
1855         /* UDL */
1856         udl=*pdup++;
1857         if (pdue-pdup>140) {
1858                 error(_("PDU data (%d) exceed maximum length of %d bytes, cut: %s"),
1859                         pdue-pdup,140,pduline);
1860                 pdue=pdup+140;
1861                 }
1862         udlb=(udl*7+7)/8;
1863         if (pdup+udlb>pdue) {
1864 size_t udl1,udlb1;
1865
1866                 udlb1=pdue-pdup;
1867                 udl1=(udlb1*8)/7;
1868                 error(_("PDU data length (%d/7->%d/8) longer than data (%d), cut to %d/7->%d/8: %s"),
1869                         udl,udlb,pdue-pdup,udl1,udlb1,pduline);
1870                 udl=udl1; udlb=udlb1;
1871                 }
1872         else
1873                 assert(pdup+udlb==pdue); /* should be checked by 'PDU length too short' above */
1874         textp=text;
1875         inb=outb=0;
1876         inreg=0; /* GCC happiness */
1877         while (udl) {
1878                 if (!inb) {
1879                         inreg=*pdup++;
1880                         inb=8;
1881                         }
1882                 if (!outb) {
1883                         assert(textp<text+160);
1884                         *textp=0x00;
1885                         outb=7;
1886                         }
1887                 xb=MIN(inb,outb);
1888 #if 0
1889                 d4("inb=%d,outb=%d,xb=%d\n",inb,outb,xb);
1890 #endif
1891                 *textp|=((inreg>>(unsigned)(8-inb))&((1<<xb)-1))<<(unsigned)(7-outb);
1892                 inb-=xb; outb-=xb;
1893                 if (!outb) {
1894                         *textp=charconv_recv(*textp,textp-text);
1895                         textp++;
1896                         udl--;
1897                         }
1898                 }
1899         *textp=0;
1900         receive_text(text);
1901 }
1902
1903 static struct {
1904         char **sp;
1905         long *ip;
1906         const char *const msg;
1907         } numarg[]={
1908                 { &maxretry,&maxretryn,"maxretry" },
1909                 { &readtime,&readtimen,"readtime" },
1910                 { &chartime,&chartimen,"chartime" },
1911                 { &cmdtime ,&cmdtimen ,"cmdtime"  },
1912                 { &baud    ,&baudn    ,"baud"     },
1913         };
1914
1915 int main(int argc,char **argv)
1916 {
1917 char *s;
1918 int i,cmgf=-1 /* GCC happiness */;
1919 unsigned fatal=0;
1920 speed_t portbaud=0 /* GCC happiness */;
1921 enum modenum argsmode;
1922 unsigned parts=0;
1923
1924         if ((s=strrchr((pname=*argv),'/'))) pname=s+1;
1925
1926 #ifdef ENABLE_NLS
1927         /* Initialize the i18n stuff */
1928         bindtextdomain(PACKAGE,LOCALEDIR);
1929         if (!setlocale(LC_ALL,""))
1930                 error("Locale not supported by C library");
1931         textdomain(PACKAGE);
1932 #endif
1933
1934 #ifdef HAVE_ATEXIT
1935         atexit(cleanup);
1936 #else
1937         error(_("atexit(3) not available at compilation time, device cleanup may be missed"));
1938 #endif
1939         signal(SIGTERM,(RETSIGTYPE (*)(int))cleanup);
1940         signal(SIGQUIT,(RETSIGTYPE (*)(int))cleanup);
1941         signal(SIGINT ,(RETSIGTYPE (*)(int))cleanup);
1942         signal(SIGHUP ,(RETSIGTYPE (*)(int))cleanup);
1943         assert(mode==MODE_UNKNOWN);
1944         for (i=0;i<NELEM(longopts);i++) {
1945                 if (longopts[i].val<MODE_FIRST) break;
1946                 if (!strstr(pname,longopts[i].name)) continue;
1947                 if (mode==MODE_UNKNOWN || mode==longopts[i].val) {
1948                         mode=longopts[i].val;
1949                         continue;
1950                         }
1951                 mode=MODE_UNKNOWN;
1952                 break;
1953                 }
1954         argsmode=mode;
1955         processargs(argc,argv,_("<command-line>"));
1956         if ((s=getenv("HOME"))) {
1957 size_t l=strlen(s);
1958 char *buf=malloc(l+50);
1959
1960                 memcpy(buf,s,l);
1961                 strcpy(buf+l,CONFIG_HOME);
1962                 readfile(buf,1);
1963                 free(buf);
1964                 }
1965         readfile(CONFIG_MAIN,1);
1966         if (verbose>=1) {
1967                 if (argsmode)
1968                         error(_(".Detected mode \"%s\" from my program name \"%s\""),MODE_NAME(argsmode),pname);
1969                 else
1970                         error(_(".Automatic mode detection unsuccessul for my progam name \"%s\""),pname);
1971                 }
1972
1973         if (!mode)
1974                 error(_("!Operation mode unset, use --send or similiar command, see help (-h)"));
1975         error(_(".Running program in mode \"%s\""),MODE_NAME(mode));
1976         switch (mode) {
1977
1978                 case MODE_SEND:           /* FALLTHRU */
1979                 case MODE_SEND_MOBILDOCK: cmdline_send     (); break;
1980                 case MODE_LOGO_SEND:      cmdline_logo_send(); break;
1981                 case MODE_RING_SEND:      cmdline_ring_send(); break;
1982                 case MODE_RECEIVE:        cmdline_receive  (); break;
1983                 default: assert(0);
1984                 }
1985         cmdline_done();
1986         for (i=0;i<NELEM(nullcheck);i++) {
1987 const struct nullcheck *n=nullcheck+i;
1988
1989                 if (*n->var) continue;
1990                 if (n->reqd && !(MODE_BIT(mode)&n->reqd)) continue;
1991                 error(_("Missing parameter \"%s\""),_(n->name));
1992                 fatal++;
1993                 }
1994         if (fatal) error(_("!Previous %s considered unrecoverable"),(fatal==1?_("error"):_("errors")));
1995         emptyclean();
1996         if (!logname) logname=DEF_LOGNAME;
1997         if (!lockfile) lockfile=DEF_LOCKFILE;
1998         if (!device) device=DEF_DEVICE;
1999
2000         for (i=0;i<NELEM(numarg);i++) {
2001 char *serr;
2002                 if (!*numarg[i].sp) continue;
2003                 *numarg[i].ip=strtol(*numarg[i].sp,&serr,0);
2004                 if (*numarg[i].ip<0 || *numarg[i].ip>=LONG_MAX || !serr || *serr)
2005                         error(_("!Number parse error for parameter \"%s\" of \"%s\" at: %s"),
2006                                 numarg[i].msg,*numarg[i].sp,serr);
2007                 }
2008         if (readtimen==-1)
2009                 readtimen=(mode==MODE_SEND_MOBILDOCK?DEF_READTIME_MOBILDOCK:DEF_READTIME);
2010         if (mode==MODE_SEND_MOBILDOCK) mode=MODE_SEND;
2011
2012         if (!strchr(device,'/')) {
2013 size_t l=strlen(device);
2014                 chk(s=malloc(5+l+1));
2015                 strcpy(s,"/dev/");
2016                 strcpy(s+5,device);
2017                 free(device);
2018                 device=s;
2019                 }
2020         devicename=strrchr(device,'/')+1; assert(!!(devicename-1));
2021         for (i=0,s=lockfile;*s;s++) {
2022                 if (*s!='%') continue;
2023                 s++;
2024                 if (*s=='%') continue;
2025                 if (*s=='s') {
2026                         if (i) error(_("!Only one \"%%s\" permitted in lockfile format-string"));
2027                         i=1; continue;
2028                         }
2029                 error(_("!Invalid format-character '%c' in lockfile format-string, only \"%%s\" allowed"),*s);
2030                 }
2031         
2032         if (*logname) {
2033                 if (!(logf=fopen(logname,"a")))
2034                         error(_("^!Error opening log \"%s\" for append"),logname);
2035                 logmsg(_("Starting up: %s"),PACKAGE " " VERSION);
2036                 }
2037
2038         switch (mode) {
2039                 case MODE_SEND:
2040                         preparebody();
2041                         genpdu();
2042                         readbody=0;
2043                         break;
2044                 case MODE_LOGO_SEND:
2045                         logoread();
2046                         break;
2047                 case MODE_RING_SEND:
2048                         ringread();
2049                         break;
2050                 case MODE_RECEIVE: break;
2051                 default: assert(0);
2052                 }
2053         if (readbody)
2054                 error(_("Warning: -f / --file is forbidden with mode \"%s\""),MODE_NAME(mode));
2055         if (smsmode) {
2056                      if (!strcmp(smsmode,"pdu" ) || !strcmp(smsmode,"0"))
2057                         force_smsmode=FSM_PDU ;
2058                 else if (!strcmp(smsmode,"text") || !strcmp(smsmode,"1"))
2059                         force_smsmode=FSM_TEXT;
2060                 else
2061                         error(_("!Unrecognized %s argument \"%s\", supported only: %s"),"-M/--smsmode",smsmode,"pdu/0/text/1");
2062                 }
2063         if (pdusmscmode) {
2064                      if (!strcmp(pdusmscmode,"count-in"))
2065                         force_pdusmscmode=FPSM_COUNT_IN;
2066                 else if (!strcmp(pdusmscmode,"count-out"))
2067                         force_pdusmscmode=FPSM_COUNT_OUT;
2068                 else if (!strcmp(pdusmscmode,"none"))
2069                         force_pdusmscmode=FPSM_NONE;
2070                 else
2071                         error(_("!Unrecognized %s argument \"%s\", supported only: %s"),"-P/--pdusmscmode",pdusmscmode,"count-in/count-out/none");
2072                 try_pdusmscmode=force_pdusmscmode;
2073                 }
2074
2075         switch (baudn) {
2076                 case  2400: portbaud= B2400; break;
2077                 case  4800: portbaud= B4800; break;
2078                 case  9600: portbaud= B9600; break;
2079                 case 19200: portbaud=B19200; break;
2080                 case 38400: portbaud=B38400; break;
2081                 case 57600: portbaud=B57600; break;
2082                 default:
2083                         error(_("!Specified baudrate %ld is not supported"),baudn);
2084                 }
2085         if (verbose>=2) error(_(".Will use baudrate %ld with hexval 0x%X"),baudn,portbaud);
2086                 
2087         if (lockfile && *lockfile && VARPRINTF(lockreal,lockfile,devicename)>0) {
2088 time_t start,end;
2089                 if (verbose>=1) error(_(".Locking device \"%s\" by \"%s\".."),device,lockreal);
2090                 time(&start);
2091                 lockdevice(0);
2092                 time(&end);
2093                 if ((end-=start)>LOCKREPORT)
2094                         logmsg(_("Device lock succeeded after %ld seconds"),(long)end);
2095                 }
2096
2097 retryopen:
2098
2099         if (verbose>=1) error(_(".Opening device \"%s\".."),device);
2100         if ((devfd=open(device,O_RDWR|O_NDELAY))<0)
2101                 error(_("^!Cannot open device \"%s\" for r/w access"),device);
2102         
2103 retryall:
2104
2105                 if (tcgetattr(devfd,&restios))
2106                         error(_("^Unable to get termios settings"));
2107                 else {
2108                         restios.c_cflag=(restios.c_cflag&~(CBAUD|CBAUDEX))|B0|HUPCL;
2109                         restios_yes=1;
2110                         }
2111                 tios.c_iflag=IGNBRK|IGNPAR|(handshake_rtscts ? 0 : IXON|IXOFF);
2112                 tios.c_oflag=0;
2113                 tios.c_cflag=CS8|CREAD|CLOCAL|HUPCL|portbaud|(handshake_rtscts ? CRTSCTS : 0);
2114                 tios.c_lflag=IEXTEN|NOFLSH;
2115                 memset(tios.c_cc,_POSIX_VDISABLE,sizeof(tios.c_cc));
2116                 tios.c_cc[VTIME]=0;
2117                 tios.c_cc[VMIN ]=1;
2118                                 cfsetispeed(&tios,portbaud);
2119                 if (cfsetospeed(&tios,portbaud)|cfsetispeed(&tios,portbaud))
2120                         error(_("^Error setting termios baudrate on device"));
2121                 if (tcflush(devfd,TCIOFLUSH))
2122                         error(_("^Error flushing termios (TCIOFLUSH) on device"));
2123                 if (tcsetattr(devfd,TCSANOW,&tios))
2124                         error(_("^!Unable to set initial termios device settings"));
2125
2126                 setalarm();
2127
2128                 devcmd("",NULL,"\r\nAT\033\032"); /* ESCAPE, CTRL-Z */
2129                 devcmd(NULL,NULL,"\r\nAT");
2130                 smscset();
2131                 if (mode==MODE_SEND || mode==MODE_RECEIVE) {
2132                         cmgf=-1;
2133                         do {
2134                                 /* condition is _negative_ here: */
2135                                 if (force_smsmode==FSM_TEXT || !devcmd(NULL,NULL,"!\r\nAT+CMGF=0")) {
2136                                         if (force_smsmode==FSM_PDU || !devcmd(NULL,NULL,"!\r\nAT+CMGF=1"))
2137                                                 { retrying(); continue; }
2138                 /* CMGF=1 */
2139                                         if (verbose>=1)
2140                                                 error(_(".Using AT+CMGF=1 (text mode).."));
2141                                         cmgf=1;
2142                                         }
2143                                 else {
2144                 /* CMGF=0 */
2145                                         if (verbose>=1)
2146                                                 error(_(".Using AT+CMGF=0 (PDU mode).."));
2147                                         cmgf=0;
2148                                         }
2149                                 } while (cmgf==-1);
2150                         }
2151                 switch (mode) {
2152                         case MODE_SEND:
2153                                 if (cmgf) {
2154                                         devcmd("\n> ",NULL,"\r\nAT+CMGS=\"%s\"",phone);
2155                                         s=devcmd(NULL,"\n+CMGS:","!~%s\032",body);
2156                                         }
2157                                 else {
2158                                         devcmd("\n> ",NULL,"\r\nAT+CMGS=%d",(
2159                                                         (try_pdusmscmode==FPSM_COUNT_IN ? strlen(pdusmsc) : 0)
2160                                                         +strlen(pdudata))/2);
2161                                         s=devcmd(NULL,"\n+CMGS:","!~%s%s\032",
2162                                                         (try_pdusmscmode!=FPSM_NONE ? pdusmsc : ""),
2163                                                         pdudata);
2164                                         if (!s && force_pdusmscmode==FPSM_AUTO) {
2165                                                 if (FPSM_MAX==try_pdusmscmode++)
2166                                                         try_pdusmscmode=FPSM_MIN;
2167                                                 else
2168                                                         retrycnt--;
2169                                                 }
2170                                         }
2171                                 break;
2172                         case MODE_LOGO_SEND:
2173                         case MODE_RING_SEND: {
2174 struct hexdata *hd;
2175
2176                                 restore="\r\nAT+CSMP=17,,0,0";
2177                                 devcmd(NULL,NULL,"\r\nAT+CSMP=81,,0,245");
2178                                 while ((hd=hexdata)) {
2179                                         devcmd("\n> ",NULL,"\r\nAT+CMGS=\"%s\"",phone);
2180                                         if (!(s=devcmd(NULL,"\n+CMGS:","!~%s\032",hd->data))) break;
2181                                         if ((hexdata=hd->next)) pushargstack_one(s,0);
2182                                         free(hd);
2183                                         parts++;
2184                                         }
2185                                 } break;
2186                         case MODE_RECEIVE:
2187                                 restore="\r\nAT+CNMI=,0";
2188                                 devcmd(NULL,NULL,"\r\nAT+CNMI=,2");
2189                                 devcmd(NULL,NULL,"\r\nAT+CSDH=0");
2190                                 for (;;) {
2191 continue_receive:
2192                                         unlockdevice(0);
2193                                         /* Never bail-out when we got up to this point */
2194                                         if (maxretryn!=-1 && verbose>=1)
2195                                                 error(_(".Initialization successful, infinite retry count set"));
2196                                         maxretryn=-1;
2197 #if RECEIVE_TEST
2198                 receive_headerparse(" \"+420602123456\",,\"99/10/25,03:21:03-00\"");
2199                 receive_accept("TESTBODY");
2200                 exit(EXIT_SUCCESS);
2201 #endif
2202                                         datawait(0);
2203                                         if (!lockdevice(1)) {
2204                                                 if (verbose>=1)
2205                                                         error(_(".Dialout detected, waiting for lock.."));
2206                                                 if (verbose>=1) error(_(".Closing device \"%s\".."),device);
2207                                                 if (close(devfd))
2208                                                         error(_("Error closing device \"%s\""),device);
2209                                                 lockdevice(0);
2210                                                 goto retryopen;
2211                                                 }
2212                                         d1("Lock-device succeeded\n");
2213                                         do {
2214                                                 d1("Reading a message for us...\n");
2215                                                 if (!(s=devcmd("\n","+CMT:"," ")))
2216                                                         goto retryall;
2217                                                 if (s==&devcmd_empty_return) /* only newlines found */
2218                                                         goto continue_receive;
2219                                                 if (cmgf && !(i=receive_headerparse(s)))
2220                                                         error(_("Receive-header parsing failed on: %s"),s);
2221                                                 if (!(s=devcmd("\n","@"," ")))
2222                                                         goto retryall;
2223                                                 if (cmgf) {
2224                                                         if (i) receive_text(s);
2225                                                         }
2226                                                 else receive_pdu(s);
2227                                                 } while (datawait(1));
2228                                         } /* return to 'continue receive' point */
2229                                 break;
2230                         default: assert(0);
2231                         }
2232                 if (!s) { retrying(); goto retryall; }
2233
2234         pushargstack_one(s,0); s=NULL;
2235         if (verbose>=1) while ((s=nextargstack())) {
2236                 while (isspace(*s)) s++;
2237                 error(_("\nMessage successfuly sent with MR (Message Reference): %s"),s);
2238                 }
2239         devcmd(NULL,NULL,"\r\nAT");
2240
2241         if (parts)
2242                 logmsg(_("SMS sent (after %d retries), %d part(s)"),retrycnt,parts);
2243         else
2244                 logmsg(_("SMS sent (after %d retries)"),retrycnt);
2245         return(EXIT_SUCCESS);
2246 }