Subversion Repositories SvarDOS

Rev

Rev 875 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
207 mateuszvis 1
/*
2
 * pkgnet - pulls SvarDOS packages from the project's online repository
3
 *
4
 * PUBLISHED UNDER THE TERMS OF THE MIT LICENSE
5
 *
558 mateuszvis 6
 * COPYRIGHT (C) 2016-2022 MATEUSZ VISTE, ALL RIGHTS RESERVED.
207 mateuszvis 7
 *
8
 * Permission is hereby granted, free of charge, to any person obtaining a
9
 * copy of this software and associated documentation files (the "Software"),
10
 * to deal in the Software without restriction, including without limitation
11
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
12
 * and/or sell copies of the Software, and to permit persons to whom the
13
 * Software is furnished to do so, subject to the following conditions:
14
 *
15
 * The above copyright notice and this permission notice shall be included in
16
 * all copies or substantial portions of the Software.
17
 *
18
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
24
 * DEALINGS IN THE SOFTWARE.
25
 *
712 mateusz.vi 26
 * http://svardos.org
207 mateuszvis 27
 */
28
 
344 mateuszvis 29
#include <direct.h> /* opendir() and friends */
207 mateuszvis 30
#include <stdio.h>
209 mateuszvis 31
#include <stdlib.h>
207 mateuszvis 32
#include <string.h>
33
#include <time.h>
34
 
35
#include "net.h"
342 mateuszvis 36
#include "unchunk.h"
207 mateuszvis 37
 
712 mateusz.vi 38
#include "svarlang.lib\svarlang.h"
39
 
633 mateusz.vi 40
#include "../../pkg/trunk/lsm.h"
344 mateuszvis 41
 
42
 
875 mateusz.vi 43
#define PVER "20220218"
558 mateuszvis 44
#define PDATE "2021-2022"
209 mateuszvis 45
 
633 mateusz.vi 46
#define HOSTADDR "svardos.org"
207 mateuszvis 47
 
209 mateuszvis 48
 
712 mateusz.vi 49
/* convenience define that outputs nls strings to screen (followed by CR/LF) */
50
#define putsnls(x,y) puts(svarlang_strid((x << 8) | y))
51
 
52
 
338 mateuszvis 53
/* returns length of all http headers, or 0 if uncomplete yet */
54
static unsigned short detecthttpheadersend(const unsigned char *buff) {
55
  char lastbyteislf = 0;
56
  unsigned short i;
57
  for (i = 0; buff[i] != 0; i++) {
207 mateuszvis 58
    if (buff[i] == '\r') continue; /* ignore CR characters */
59
    if (buff[i] != '\n') {
60
      lastbyteislf = 0;
61
      continue;
62
    }
63
    /* cur byte is LF -> if last one was also LF then this is an empty line, meaning headers are over */
64
    if (lastbyteislf == 0) {
65
      lastbyteislf = 1;
66
      continue;
67
    }
338 mateuszvis 68
    /* end of headers! return length of headers */
69
    return(i + 1); /* add 1 to skip the current \n character */
207 mateuszvis 70
  }
71
  return(0);
72
}
73
 
74
 
209 mateuszvis 75
static void help(void) {
76
  puts("pkgnet ver " PVER " -- Copyright (C) " PDATE " Mateusz Viste");
77
  puts("");
712 mateusz.vi 78
  putsnls(1, 0);  /* "pkgnet is the SvarDOS package downloader" */
209 mateuszvis 79
  puts("");
712 mateusz.vi 80
  putsnls(1, 1);  /* "usage:  pkgnet search <term>" */
81
  putsnls(1, 2);  /* "        pkgnet pull <package>" */
82
  putsnls(1, 3);  /* "        pkgnet pull <package>-<version>" */
875 mateusz.vi 83
  putsnls(1, 4);  /* "        pkgnet pullsrc <package>" */
84
  putsnls(1, 5);  /* "        pkgnet pullsrc <package>-<version>" */
712 mateusz.vi 85
  putsnls(1, 6);  /* "        pkgnet checkup" */
209 mateuszvis 86
  puts("");
712 mateusz.vi 87
  putsnls(1, 7);  /* "actions:" */
209 mateuszvis 88
  puts("");
712 mateusz.vi 89
  putsnls(1, 8);  /* "search   - asks remote repository for the list of matching packages" */
90
  putsnls(1, 9);  /* "pull     - downloads package into current directory" */
91
  putsnls(1, 10); /* "checkup  - lists updates available for your system" */
92
  puts("");
342 mateuszvis 93
  printf("Watt32 kernel: %s", net_engine());
94
  puts("");
209 mateuszvis 95
}
96
 
97
 
98
/* parses command line arguments and fills outfname and url accordingly
99
 * returns 0 on success, non-zero otherwise */
342 mateuszvis 100
static int parseargv(int argc, char * const *argv, char *outfname, char *url, int *ispost) {
725 mateusz.vi 101
  const char *lang = getenv("LANG");
102
  if (lang == NULL) lang = "";
211 mateuszvis 103
  *outfname = 0;
209 mateuszvis 104
  *url = 0;
342 mateuszvis 105
  *ispost = 0;
209 mateuszvis 106
  if ((argc == 3) && (strcasecmp(argv[1], "search") == 0)) {
725 mateusz.vi 107
    sprintf(url, "/repo/?a=search&p=%s&lang=%s", argv[2], lang);
875 mateusz.vi 108
  } else if ((argc == 3) && ((strcasecmp(argv[1], "pull") == 0) || (strcasecmp(argv[1], "pullsrc") == 0))) {
558 mateuszvis 109
    unsigned short i;
110
    /* copy argv[2] into outfname, but stop at first '-' or null terminator
111
     * this trims any '-version' part in filename to respect 8+3 */
112
    for (i = 0; (argv[2][i] != 0) && (argv[2][i] != '-') && (i < 8); i++) {
113
      outfname[i] = argv[2][i];
211 mateuszvis 114
    }
875 mateusz.vi 115
    /* add the extension (svp or zip) to filename and compute url */
116
    if (strcasecmp(argv[1], "pull") == 0) {
117
      sprintf(url, "/repo/?a=pull&p=%s&lang=%s", argv[2], lang);
118
      strcpy(outfname + i, ".svp");
119
    } else {
120
      sprintf(url, "/repo/?a=pullsrc&p=%s&lang=%s", argv[2], lang);
121
      strcpy(outfname + i, ".zip");
122
    }
209 mateuszvis 123
  } else if ((argc == 2) && (strcasecmp(argv[1], "checkup") == 0)) {
725 mateusz.vi 124
    sprintf(url, "/repo/?a=checkup&lang=%s", lang);
342 mateuszvis 125
    *ispost = 1;
209 mateuszvis 126
  } else {
127
    help();
128
    return(-1);
129
  }
130
  return(0);
131
}
132
 
133
 
342 mateuszvis 134
static int htget_headers(unsigned char *buffer, size_t buffersz, struct net_tcpsocket *sock, int *httpcode, int *ischunked)  {
338 mateuszvis 135
  unsigned char *buffptr = buffer;
136
  unsigned short bufflen = 0;
137
  int byteread;
138
  time_t starttime = time(NULL);
139
  for (;;) {
140
    byteread = net_recv(sock, buffptr, buffersz - (bufflen + 1)); /* -1 because I will append a NULL terminator */
141
 
142
    if (byteread > 0) { /* got data */
143
      int hdlen;
144
      bufflen += byteread;
145
      buffptr += byteread;
146
      buffer[bufflen] = 0;
147
      hdlen = detecthttpheadersend(buffer);
148
      if (hdlen > 0) { /* full headers - parse http code and continue processing */
342 mateuszvis 149
        int i;
150
        buffer[hdlen - 1] = 0;
338 mateuszvis 151
        /* find the first space (HTTP/1.1 200 OK) */
342 mateuszvis 152
        for (i = 0; i < 16; i++) {
153
          if ((buffer[i] == ' ') || (buffer[i] == 0)) break;
338 mateuszvis 154
        }
342 mateuszvis 155
        if (buffer[i] != ' ') return(-1);
156
        *httpcode = atoi((char *)(buffer + i + 1));
157
        /* switch all headers to low-case so it is easier to parse them */
158
        for (i = 0; i < hdlen; i++) if ((buffer[i] >= 'A') && (buffer[i] <= 'Z')) buffer[i] += ('a' - 'A');
159
        /* look out for chunked transfer encoding */
160
        {
161
        char *lineptr = strstr((char *)buffer, "\ntransfer-encoding:");
162
        if (lineptr != NULL) {
163
          lineptr += 19;
164
          /* replace nearest \r, \n or 0 by 0 */
165
          for (i = 0; ; i++) {
166
            if ((lineptr[i] == '\r') || (lineptr[i] == '\n') || (lineptr[i] == 0)) {
167
              lineptr[i] = 0;
168
              break;
169
            }
170
          }
171
          /* do I see the 'chunked' word? */
172
          if (strstr((char *)lineptr, "chunked") != NULL) *ischunked = 1;
173
        }
174
        }
338 mateuszvis 175
        /* rewind the buffer */
176
        bufflen -= hdlen;
177
        memmove(buffer, buffer + hdlen, bufflen);
178
        return(bufflen); /* move to body processing now */
179
      }
180
 
181
    } else if (byteread < 0) { /* abort on error */
182
      return(-2); /* unexpected end of connection (while waiting for all http headers) */
183
 
184
    } else { /* else no data received - look for timeout and release a cpu cycle */
185
      if (time(NULL) - starttime > 20) return(-3); /* TIMEOUT! */
186
      _asm int 28h; /* release a CPU cycle */
187
    }
188
  }
189
}
190
 
191
 
342 mateuszvis 192
/* provides body data of the POST query for checkup actions
193
   fills buff with data and returns data length.
194
   must be called repeateadly until zero-lengh is returned */
195
static unsigned short checkupdata(char *buff) {
344 mateuszvis 196
  static char *dosdir = NULL;
197
  static DIR *dp;
198
  static struct dirent *ep;
199
 
200
  /* make sure I know %DOSDIR% */
201
  if (dosdir == NULL) {
202
    dosdir = getenv("DOSDIR");
203
    if ((dosdir == NULL) || (dosdir[0] == 0)) {
712 mateusz.vi 204
      putsnls(9, 0); /* "ERROR: %DOSDIR% not set" */
344 mateuszvis 205
      return(0);
206
    }
207
  }
208
 
209
  /* if first call, open the package directory */
210
  if (dp == NULL) {
211
    sprintf(buff, "%s\\packages", dosdir);
212
    dp = opendir(buff);
213
    if (dp == NULL) {
712 mateusz.vi 214
      putsnls(9, 1); /* "ERROR: Could not access %DOSDIR%\\packages directory" */
344 mateuszvis 215
      return(0);
216
    }
217
  }
218
 
219
  for (;;) {
220
    int tlen;
347 mateuszvis 221
    char ver[20];
344 mateuszvis 222
    ep = readdir(dp);   /* readdir() result must never be freed (statically allocated) */
223
    if (ep == NULL) {   /* no more entries */
224
      closedir(dp);
225
      return(0);
226
    }
227
 
228
    tlen = strlen(ep->d_name);
229
    if (tlen < 4) continue; /* files must be at least 5 bytes long ("x.lst") */
230
    if (strcasecmp(ep->d_name + tlen - 4, ".lst") != 0) continue;  /* if not an .lst file, skip it silently */
231
    ep->d_name[tlen - 4] = 0; /* trim out the ".lst" suffix */
232
 
233
    /* load the metadata from %DOSDIR\APPINFO\*.lsm */
234
    sprintf(buff, "%s\\appinfo\\%s.lsm", dosdir, ep->d_name);
235
    readlsm(buff, ver, sizeof(ver));
236
 
346 mateuszvis 237
    return(sprintf(buff, "%s\t%s\n", ep->d_name, ver));
344 mateuszvis 238
  }
342 mateuszvis 239
}
240
 
241
 
211 mateuszvis 242
/* fetch http data from ipaddr using url
243
 * write result to file outfname if not null, or print to stdout otherwise
244
 * fills bsum with the BSD sum of the data
342 mateuszvis 245
 * is ispost is non-zero, then the request is a POST and its body data is
246
 * obtained through repeated calls to checkupdata()
211 mateuszvis 247
 * returns the length of data obtained, or neg value on error */
342 mateuszvis 248
static long htget(const char *ipaddr, const char *url, const char *outfname, unsigned short *bsum, int ispost, unsigned char *buffer, size_t buffersz) {
211 mateuszvis 249
  struct net_tcpsocket *sock;
327 mateuszvis 250
  time_t lastactivity, lastprogressoutput = 0;
342 mateuszvis 251
  int httpcode = -1, ischunked = 0;
338 mateuszvis 252
  int byteread;
332 mateuszvis 253
  long flen = 0, lastflen = 0;
209 mateuszvis 254
  FILE *fd = NULL;
207 mateuszvis 255
 
342 mateuszvis 256
  /* unchunk state variable is using a little part of the supplied buffer */
257
  struct unchunk_state *unchstate = (void *)buffer;
258
  buffer += sizeof(*unchstate);
259
  buffersz -= sizeof(*unchstate);
260
  memset(unchstate, 0, sizeof(*unchstate));
261
 
211 mateuszvis 262
  sock = net_connect(ipaddr, 80);
207 mateuszvis 263
  if (sock == NULL) {
712 mateusz.vi 264
    printf(svarlang_strid(0x0902), HOSTADDR); /* "ERROR: failed to connect to " HOSTADDR */
265
    puts("");
207 mateuszvis 266
    goto SHITQUIT;
267
  }
268
 
269
  /* wait for net_connect() to actually connect */
270
  for (;;) {
329 mateuszvis 271
    int connstate = net_isconnected(sock);
207 mateuszvis 272
    if (connstate > 0) break;
273
    if (connstate < 0) {
712 mateusz.vi 274
      printf(svarlang_strid(0x0902), HOSTADDR); /* "ERROR: failed to connect to " HOSTADDR */
275
      puts("");
207 mateuszvis 276
      goto SHITQUIT;
277
    }
211 mateuszvis 278
    _asm int 28h;  /* DOS idle */
207 mateuszvis 279
  }
280
 
330 mateuszvis 281
  /* socket is connected - send the http request (MUST be HTTP/1.0 because I do not support chunked transfers!) */
342 mateuszvis 282
  if (ispost) {
283
    snprintf((char *)buffer, buffersz, "POST %s HTTP/1.1\r\nHOST: " HOSTADDR "\r\nUSER-AGENT: pkgnet/" PVER "\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n", url);
284
  } else {
285
    snprintf((char *)buffer, buffersz, "GET %s HTTP/1.1\r\nHOST: " HOSTADDR "\r\nUSER-AGENT: pkgnet/" PVER "\r\nConnection: close\r\n\r\n", url);
286
  }
207 mateuszvis 287
 
329 mateuszvis 288
  if (net_send(sock, buffer, strlen((char *)buffer)) != (int)strlen((char *)buffer)) {
712 mateusz.vi 289
    putsnls(9, 3); /* "ERROR: failed to send a HTTP query to remote server" */
207 mateuszvis 290
    goto SHITQUIT;
291
  }
292
 
342 mateuszvis 293
  /* send chunked data for POST queries */
294
  if (ispost) {
295
    unsigned short blen;
296
    int hlen;
297
    char *hbuf = (char *)buffer + buffersz - 16;
344 mateuszvis 298
    do {
342 mateuszvis 299
      blen = checkupdata((char *)buffer);
300
      if (blen == 0) { /* last item contains the message trailer */
344 mateuszvis 301
        hlen = sprintf(hbuf, "0\r\n");
342 mateuszvis 302
      } else {
303
        hlen = sprintf(hbuf, "%X\r\n", blen);
304
      }
305
      if (net_send(sock, hbuf, hlen) != hlen) {
712 mateusz.vi 306
        putsnls(9, 4); /* "ERROR: failed to send POST data to remote server" */
342 mateuszvis 307
        goto SHITQUIT;
308
      }
344 mateuszvis 309
      /* add trailing CR/LF to buffer as required by chunked mode */
310
      buffer[blen++] = '\r';
311
      buffer[blen++] = '\n';
342 mateuszvis 312
      if (net_send(sock, buffer, blen) != blen) {
712 mateusz.vi 313
        putsnls(9, 4); /* "ERROR: failed to send POST data to remote server" */
342 mateuszvis 314
        goto SHITQUIT;
315
      }
344 mateuszvis 316
    } while (blen != 2);
342 mateuszvis 317
  }
318
 
338 mateuszvis 319
  /* receive and process HTTP headers */
342 mateuszvis 320
  byteread = htget_headers(buffer, buffersz, sock, &httpcode, &ischunked);
207 mateuszvis 321
 
338 mateuszvis 322
  /* transmission error? */
323
  if (byteread < 0) {
712 mateusz.vi 324
    printf(svarlang_strid(0x0905), byteread); /* "ERROR: TCP communication error #%d" */
338 mateuszvis 325
    puts("");
326
    goto SHITQUIT;
327
  }
207 mateuszvis 328
 
338 mateuszvis 329
  /* open destination file if required and if no server-side error occured */
342 mateuszvis 330
  if ((httpcode >= 200) && (httpcode <= 299) && (*outfname != 0)) {
338 mateuszvis 331
    fd = fopen(outfname, "wb");
332
    if (fd == NULL) {
712 mateusz.vi 333
      printf(svarlang_strid(0x0906), outfname); /* "ERROR: failed to create file %s" */
338 mateuszvis 334
      puts("");
335
      goto SHITQUIT;
207 mateuszvis 336
    }
338 mateuszvis 337
  }
207 mateuszvis 338
 
342 mateuszvis 339
  /* read body of the answer (and chunk-decode it if needed) */
338 mateuszvis 340
  lastactivity = time(NULL);
342 mateuszvis 341
  for (;; byteread = net_recv(sock, buffer, buffersz - 1)) { /* read 1 byte less because I need to append a NULL terminator when printf'ing the content */
338 mateuszvis 342
 
343
    if (byteread > 0) { /* got data */
207 mateuszvis 344
      lastactivity = time(NULL);
342 mateuszvis 345
 
346
      /* unpack data if server transmits in chunked mode */
347
      if (ischunked) byteread = unchunk(buffer, byteread, unchstate);
348
 
207 mateuszvis 349
      /* if downloading to file, write stuff to disk */
209 mateuszvis 350
      if (fd != NULL) {
351
        int i;
352
        if (fwrite(buffer, 1, byteread, fd) != byteread) {
712 mateusz.vi 353
          printf(svarlang_strid(0x0907), outfname, flen); /* "ERROR: failed to write data to file %s after %ld bytes" */
209 mateuszvis 354
          puts("");
355
          break;
356
        }
357
        flen += byteread;
327 mateuszvis 358
        /* update progress once a sec */
359
        if (lastprogressoutput != lastactivity) {
360
          lastprogressoutput = lastactivity;
333 mateuszvis 361
          printf("%ld KiB (%ld KiB/s)     \r", flen >> 10, (flen >> 10) - (lastflen >> 10)); /* trailing spaces are meant to avoid leaving garbage on screen if speed goes from, say, 1000 KiB/s to 9 KiB/s */
332 mateuszvis 362
          lastflen = flen;
363
          fflush(stdout); /* avoid console buffering */
327 mateuszvis 364
        }
209 mateuszvis 365
        /* update the bsd sum */
366
        for (i = 0; i < byteread; i++) {
367
          /* rotr16 */
211 mateuszvis 368
          unsigned short bsumlsb = *bsum & 1;
369
          *bsum >>= 1;
370
          *bsum |= (bsumlsb << 15);
371
          *bsum += buffer[i];
209 mateuszvis 372
        }
373
      } else { /* otherwise dump to screen */
342 mateuszvis 374
        buffer[byteread] = 0;
209 mateuszvis 375
        printf("%s", buffer);
376
      }
338 mateuszvis 377
 
378
    } else if (byteread < 0) { /* end of connection */
379
      break;
380
 
381
    } else { /* check for timeout (byteread == 0) */
382
      if (time(NULL) - lastactivity > 20) { /* TIMEOUT! */
712 mateusz.vi 383
        putsnls(9, 8); /* "ERROR: Timeout while waiting for data" */
338 mateuszvis 384
        goto SHITQUIT;
385
      }
386
      /* waiting for packets - release a CPU cycle in the meantime */
387
      _asm int 28h;
207 mateuszvis 388
    }
389
  }
390
 
338 mateuszvis 391
  goto ALLGOOD;
392
 
211 mateuszvis 393
  SHITQUIT:
338 mateuszvis 394
  flen = -1;
395
 
396
  ALLGOOD:
397
  if (fd != NULL) fclose(fd);
333 mateuszvis 398
  net_close(sock);
338 mateuszvis 399
  return(flen);
211 mateuszvis 400
}
401
 
402
 
403
/* checks if file exists, returns 0 if not, non-zero otherwise */
404
static int fexists(const char *fname) {
405
  FILE *fd = fopen(fname, "rb");
406
  if (fd == NULL) return(0);
407
  fclose(fd);
408
  return(1);
409
}
410
 
411
 
412
int main(int argc, char **argv) {
413
  unsigned short bsum = 0;
414
  long flen;
342 mateuszvis 415
  int ispost; /* is the request a POST? */
211 mateuszvis 416
 
342 mateuszvis 417
  struct {
418
    unsigned char buffer[5000];
419
    char ipaddr[64];
420
    char url[64];
421
    char outfname[16];
422
  } *mem;
423
 
712 mateusz.vi 424
  svarlang_autoload("PKGNET");
425
 
342 mateuszvis 426
  /* allocate memory */
427
  mem = malloc(sizeof(*mem));
428
  if (mem == NULL) {
712 mateusz.vi 429
    putsnls(9, 9); /* "ERROR: out of memory" */
342 mateuszvis 430
    return(1);
431
  }
432
 
211 mateuszvis 433
  /* parse command line arguments */
342 mateuszvis 434
  if (parseargv(argc, argv, mem->outfname, mem->url, &ispost) != 0) return(1);
211 mateuszvis 435
 
436
  /* if outfname requested, make sure that file does not exist yet */
342 mateuszvis 437
  if ((mem->outfname[0] != 0) && (fexists(mem->outfname))) {
712 mateusz.vi 438
    printf(svarlang_strid(0x090A), mem->outfname); /* "ERROR: file %s already exists" */
211 mateuszvis 439
    puts("");
440
    return(1);
441
  }
442
 
443
  /* init network stack */
444
  if (net_init() != 0) {
712 mateusz.vi 445
    putsnls(9, 11); /* "ERROR: Network subsystem initialization failed" */
211 mateuszvis 446
    return(1);
447
  }
448
 
449
  puts(""); /* required because watt-32 likes to print out garbage sometimes ("configuring through DHCP...") */
450
 
342 mateuszvis 451
  if (net_dnsresolve(mem->ipaddr, HOSTADDR) != 0) {
712 mateusz.vi 452
    putsnls(9, 12); /* "ERROR: DNS resolution failed" */
211 mateuszvis 453
    return(1);
454
  }
455
 
342 mateuszvis 456
  flen = htget(mem->ipaddr, mem->url, mem->outfname, &bsum, ispost, mem->buffer, sizeof(mem->buffer));
211 mateuszvis 457
  if (flen < 1) return(1);
458
 
342 mateuszvis 459
  if (mem->outfname[0] != 0) {
209 mateuszvis 460
    /* print bsum, size, filename */
712 mateusz.vi 461
    printf(svarlang_strid(0x0200), flen >> 10, mem->outfname, bsum); /* Downloaded %ld KiB into %s (BSUM: %04X) */
209 mateuszvis 462
    puts("");
463
  }
464
 
207 mateuszvis 465
  return(0);
466
}