Subversion Repositories SvarDOS

Rev

Rev 675 | Rev 725 | Go to most recent revision | 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
 
712 mateusz.vi 43
#define PVER "20220215"
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>" */
83
  putsnls(1, 6);  /* "        pkgnet checkup" */
209 mateuszvis 84
  puts("");
712 mateusz.vi 85
  putsnls(1, 7);  /* "actions:" */
209 mateuszvis 86
  puts("");
712 mateusz.vi 87
  putsnls(1, 8);  /* "search   - asks remote repository for the list of matching packages" */
88
  putsnls(1, 9);  /* "pull     - downloads package into current directory" */
89
  putsnls(1, 10); /* "checkup  - lists updates available for your system" */
90
  puts("");
342 mateuszvis 91
  printf("Watt32 kernel: %s", net_engine());
92
  puts("");
209 mateuszvis 93
}
94
 
95
 
96
/* parses command line arguments and fills outfname and url accordingly
97
 * returns 0 on success, non-zero otherwise */
342 mateuszvis 98
static int parseargv(int argc, char * const *argv, char *outfname, char *url, int *ispost) {
211 mateuszvis 99
  *outfname = 0;
209 mateuszvis 100
  *url = 0;
342 mateuszvis 101
  *ispost = 0;
209 mateuszvis 102
  if ((argc == 3) && (strcasecmp(argv[1], "search") == 0)) {
214 mateuszvis 103
    sprintf(url, "/repo/?a=search&p=%s", argv[2]);
209 mateuszvis 104
  } else if ((argc == 3) && (strcasecmp(argv[1], "pull") == 0)) {
558 mateuszvis 105
    unsigned short i;
106
    sprintf(url, "/repo/?a=pull&p=%s", argv[2]);
107
    /* copy argv[2] into outfname, but stop at first '-' or null terminator
108
     * this trims any '-version' part in filename to respect 8+3 */
109
    for (i = 0; (argv[2][i] != 0) && (argv[2][i] != '-') && (i < 8); i++) {
110
      outfname[i] = argv[2][i];
211 mateuszvis 111
    }
675 mateusz.vi 112
    /* add the svp extension to filename */
113
    strcpy(outfname + i, ".svp");
209 mateuszvis 114
  } else if ((argc == 2) && (strcasecmp(argv[1], "checkup") == 0)) {
342 mateuszvis 115
    sprintf(url, "/repo/?a=checkup");
116
    *ispost = 1;
209 mateuszvis 117
  } else {
118
    help();
119
    return(-1);
120
  }
121
  return(0);
122
}
123
 
124
 
342 mateuszvis 125
static int htget_headers(unsigned char *buffer, size_t buffersz, struct net_tcpsocket *sock, int *httpcode, int *ischunked)  {
338 mateuszvis 126
  unsigned char *buffptr = buffer;
127
  unsigned short bufflen = 0;
128
  int byteread;
129
  time_t starttime = time(NULL);
130
  for (;;) {
131
    byteread = net_recv(sock, buffptr, buffersz - (bufflen + 1)); /* -1 because I will append a NULL terminator */
132
 
133
    if (byteread > 0) { /* got data */
134
      int hdlen;
135
      bufflen += byteread;
136
      buffptr += byteread;
137
      buffer[bufflen] = 0;
138
      hdlen = detecthttpheadersend(buffer);
139
      if (hdlen > 0) { /* full headers - parse http code and continue processing */
342 mateuszvis 140
        int i;
141
        buffer[hdlen - 1] = 0;
338 mateuszvis 142
        /* find the first space (HTTP/1.1 200 OK) */
342 mateuszvis 143
        for (i = 0; i < 16; i++) {
144
          if ((buffer[i] == ' ') || (buffer[i] == 0)) break;
338 mateuszvis 145
        }
342 mateuszvis 146
        if (buffer[i] != ' ') return(-1);
147
        *httpcode = atoi((char *)(buffer + i + 1));
148
        /* switch all headers to low-case so it is easier to parse them */
149
        for (i = 0; i < hdlen; i++) if ((buffer[i] >= 'A') && (buffer[i] <= 'Z')) buffer[i] += ('a' - 'A');
150
        /* look out for chunked transfer encoding */
151
        {
152
        char *lineptr = strstr((char *)buffer, "\ntransfer-encoding:");
153
        if (lineptr != NULL) {
154
          lineptr += 19;
155
          /* replace nearest \r, \n or 0 by 0 */
156
          for (i = 0; ; i++) {
157
            if ((lineptr[i] == '\r') || (lineptr[i] == '\n') || (lineptr[i] == 0)) {
158
              lineptr[i] = 0;
159
              break;
160
            }
161
          }
162
          /* do I see the 'chunked' word? */
163
          if (strstr((char *)lineptr, "chunked") != NULL) *ischunked = 1;
164
        }
165
        }
338 mateuszvis 166
        /* rewind the buffer */
167
        bufflen -= hdlen;
168
        memmove(buffer, buffer + hdlen, bufflen);
169
        return(bufflen); /* move to body processing now */
170
      }
171
 
172
    } else if (byteread < 0) { /* abort on error */
173
      return(-2); /* unexpected end of connection (while waiting for all http headers) */
174
 
175
    } else { /* else no data received - look for timeout and release a cpu cycle */
176
      if (time(NULL) - starttime > 20) return(-3); /* TIMEOUT! */
177
      _asm int 28h; /* release a CPU cycle */
178
    }
179
  }
180
}
181
 
182
 
342 mateuszvis 183
/* provides body data of the POST query for checkup actions
184
   fills buff with data and returns data length.
185
   must be called repeateadly until zero-lengh is returned */
186
static unsigned short checkupdata(char *buff) {
344 mateuszvis 187
  static char *dosdir = NULL;
188
  static DIR *dp;
189
  static struct dirent *ep;
190
 
191
  /* make sure I know %DOSDIR% */
192
  if (dosdir == NULL) {
193
    dosdir = getenv("DOSDIR");
194
    if ((dosdir == NULL) || (dosdir[0] == 0)) {
712 mateusz.vi 195
      putsnls(9, 0); /* "ERROR: %DOSDIR% not set" */
344 mateuszvis 196
      return(0);
197
    }
198
  }
199
 
200
  /* if first call, open the package directory */
201
  if (dp == NULL) {
202
    sprintf(buff, "%s\\packages", dosdir);
203
    dp = opendir(buff);
204
    if (dp == NULL) {
712 mateusz.vi 205
      putsnls(9, 1); /* "ERROR: Could not access %DOSDIR%\\packages directory" */
344 mateuszvis 206
      return(0);
207
    }
208
  }
209
 
210
  for (;;) {
211
    int tlen;
347 mateuszvis 212
    char ver[20];
344 mateuszvis 213
    ep = readdir(dp);   /* readdir() result must never be freed (statically allocated) */
214
    if (ep == NULL) {   /* no more entries */
215
      closedir(dp);
216
      return(0);
217
    }
218
 
219
    tlen = strlen(ep->d_name);
220
    if (tlen < 4) continue; /* files must be at least 5 bytes long ("x.lst") */
221
    if (strcasecmp(ep->d_name + tlen - 4, ".lst") != 0) continue;  /* if not an .lst file, skip it silently */
222
    ep->d_name[tlen - 4] = 0; /* trim out the ".lst" suffix */
223
 
224
    /* load the metadata from %DOSDIR\APPINFO\*.lsm */
225
    sprintf(buff, "%s\\appinfo\\%s.lsm", dosdir, ep->d_name);
226
    readlsm(buff, ver, sizeof(ver));
227
 
346 mateuszvis 228
    return(sprintf(buff, "%s\t%s\n", ep->d_name, ver));
344 mateuszvis 229
  }
342 mateuszvis 230
}
231
 
232
 
211 mateuszvis 233
/* fetch http data from ipaddr using url
234
 * write result to file outfname if not null, or print to stdout otherwise
235
 * fills bsum with the BSD sum of the data
342 mateuszvis 236
 * is ispost is non-zero, then the request is a POST and its body data is
237
 * obtained through repeated calls to checkupdata()
211 mateuszvis 238
 * returns the length of data obtained, or neg value on error */
342 mateuszvis 239
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 240
  struct net_tcpsocket *sock;
327 mateuszvis 241
  time_t lastactivity, lastprogressoutput = 0;
342 mateuszvis 242
  int httpcode = -1, ischunked = 0;
338 mateuszvis 243
  int byteread;
332 mateuszvis 244
  long flen = 0, lastflen = 0;
209 mateuszvis 245
  FILE *fd = NULL;
207 mateuszvis 246
 
342 mateuszvis 247
  /* unchunk state variable is using a little part of the supplied buffer */
248
  struct unchunk_state *unchstate = (void *)buffer;
249
  buffer += sizeof(*unchstate);
250
  buffersz -= sizeof(*unchstate);
251
  memset(unchstate, 0, sizeof(*unchstate));
252
 
211 mateuszvis 253
  sock = net_connect(ipaddr, 80);
207 mateuszvis 254
  if (sock == NULL) {
712 mateusz.vi 255
    printf(svarlang_strid(0x0902), HOSTADDR); /* "ERROR: failed to connect to " HOSTADDR */
256
    puts("");
207 mateuszvis 257
    goto SHITQUIT;
258
  }
259
 
260
  /* wait for net_connect() to actually connect */
261
  for (;;) {
329 mateuszvis 262
    int connstate = net_isconnected(sock);
207 mateuszvis 263
    if (connstate > 0) break;
264
    if (connstate < 0) {
712 mateusz.vi 265
      printf(svarlang_strid(0x0902), HOSTADDR); /* "ERROR: failed to connect to " HOSTADDR */
266
      puts("");
207 mateuszvis 267
      goto SHITQUIT;
268
    }
211 mateuszvis 269
    _asm int 28h;  /* DOS idle */
207 mateuszvis 270
  }
271
 
330 mateuszvis 272
  /* socket is connected - send the http request (MUST be HTTP/1.0 because I do not support chunked transfers!) */
342 mateuszvis 273
  if (ispost) {
274
    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);
275
  } else {
276
    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);
277
  }
207 mateuszvis 278
 
329 mateuszvis 279
  if (net_send(sock, buffer, strlen((char *)buffer)) != (int)strlen((char *)buffer)) {
712 mateusz.vi 280
    putsnls(9, 3); /* "ERROR: failed to send a HTTP query to remote server" */
207 mateuszvis 281
    goto SHITQUIT;
282
  }
283
 
342 mateuszvis 284
  /* send chunked data for POST queries */
285
  if (ispost) {
286
    unsigned short blen;
287
    int hlen;
288
    char *hbuf = (char *)buffer + buffersz - 16;
344 mateuszvis 289
    do {
342 mateuszvis 290
      blen = checkupdata((char *)buffer);
291
      if (blen == 0) { /* last item contains the message trailer */
344 mateuszvis 292
        hlen = sprintf(hbuf, "0\r\n");
342 mateuszvis 293
      } else {
294
        hlen = sprintf(hbuf, "%X\r\n", blen);
295
      }
296
      if (net_send(sock, hbuf, hlen) != hlen) {
712 mateusz.vi 297
        putsnls(9, 4); /* "ERROR: failed to send POST data to remote server" */
342 mateuszvis 298
        goto SHITQUIT;
299
      }
344 mateuszvis 300
      /* add trailing CR/LF to buffer as required by chunked mode */
301
      buffer[blen++] = '\r';
302
      buffer[blen++] = '\n';
342 mateuszvis 303
      if (net_send(sock, buffer, blen) != blen) {
712 mateusz.vi 304
        putsnls(9, 4); /* "ERROR: failed to send POST data to remote server" */
342 mateuszvis 305
        goto SHITQUIT;
306
      }
344 mateuszvis 307
    } while (blen != 2);
342 mateuszvis 308
  }
309
 
338 mateuszvis 310
  /* receive and process HTTP headers */
342 mateuszvis 311
  byteread = htget_headers(buffer, buffersz, sock, &httpcode, &ischunked);
207 mateuszvis 312
 
338 mateuszvis 313
  /* transmission error? */
314
  if (byteread < 0) {
712 mateusz.vi 315
    printf(svarlang_strid(0x0905), byteread); /* "ERROR: TCP communication error #%d" */
338 mateuszvis 316
    puts("");
317
    goto SHITQUIT;
318
  }
207 mateuszvis 319
 
338 mateuszvis 320
  /* open destination file if required and if no server-side error occured */
342 mateuszvis 321
  if ((httpcode >= 200) && (httpcode <= 299) && (*outfname != 0)) {
338 mateuszvis 322
    fd = fopen(outfname, "wb");
323
    if (fd == NULL) {
712 mateusz.vi 324
      printf(svarlang_strid(0x0906), outfname); /* "ERROR: failed to create file %s" */
338 mateuszvis 325
      puts("");
326
      goto SHITQUIT;
207 mateuszvis 327
    }
338 mateuszvis 328
  }
207 mateuszvis 329
 
342 mateuszvis 330
  /* read body of the answer (and chunk-decode it if needed) */
338 mateuszvis 331
  lastactivity = time(NULL);
342 mateuszvis 332
  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 333
 
334
    if (byteread > 0) { /* got data */
207 mateuszvis 335
      lastactivity = time(NULL);
342 mateuszvis 336
 
337
      /* unpack data if server transmits in chunked mode */
338
      if (ischunked) byteread = unchunk(buffer, byteread, unchstate);
339
 
207 mateuszvis 340
      /* if downloading to file, write stuff to disk */
209 mateuszvis 341
      if (fd != NULL) {
342
        int i;
343
        if (fwrite(buffer, 1, byteread, fd) != byteread) {
712 mateusz.vi 344
          printf(svarlang_strid(0x0907), outfname, flen); /* "ERROR: failed to write data to file %s after %ld bytes" */
209 mateuszvis 345
          puts("");
346
          break;
347
        }
348
        flen += byteread;
327 mateuszvis 349
        /* update progress once a sec */
350
        if (lastprogressoutput != lastactivity) {
351
          lastprogressoutput = lastactivity;
333 mateuszvis 352
          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 353
          lastflen = flen;
354
          fflush(stdout); /* avoid console buffering */
327 mateuszvis 355
        }
209 mateuszvis 356
        /* update the bsd sum */
357
        for (i = 0; i < byteread; i++) {
358
          /* rotr16 */
211 mateuszvis 359
          unsigned short bsumlsb = *bsum & 1;
360
          *bsum >>= 1;
361
          *bsum |= (bsumlsb << 15);
362
          *bsum += buffer[i];
209 mateuszvis 363
        }
364
      } else { /* otherwise dump to screen */
342 mateuszvis 365
        buffer[byteread] = 0;
209 mateuszvis 366
        printf("%s", buffer);
367
      }
338 mateuszvis 368
 
369
    } else if (byteread < 0) { /* end of connection */
370
      break;
371
 
372
    } else { /* check for timeout (byteread == 0) */
373
      if (time(NULL) - lastactivity > 20) { /* TIMEOUT! */
712 mateusz.vi 374
        putsnls(9, 8); /* "ERROR: Timeout while waiting for data" */
338 mateuszvis 375
        goto SHITQUIT;
376
      }
377
      /* waiting for packets - release a CPU cycle in the meantime */
378
      _asm int 28h;
207 mateuszvis 379
    }
380
  }
381
 
338 mateuszvis 382
  goto ALLGOOD;
383
 
211 mateuszvis 384
  SHITQUIT:
338 mateuszvis 385
  flen = -1;
386
 
387
  ALLGOOD:
388
  if (fd != NULL) fclose(fd);
333 mateuszvis 389
  net_close(sock);
338 mateuszvis 390
  return(flen);
211 mateuszvis 391
}
392
 
393
 
394
/* checks if file exists, returns 0 if not, non-zero otherwise */
395
static int fexists(const char *fname) {
396
  FILE *fd = fopen(fname, "rb");
397
  if (fd == NULL) return(0);
398
  fclose(fd);
399
  return(1);
400
}
401
 
402
 
403
int main(int argc, char **argv) {
404
  unsigned short bsum = 0;
405
  long flen;
342 mateuszvis 406
  int ispost; /* is the request a POST? */
211 mateuszvis 407
 
342 mateuszvis 408
  struct {
409
    unsigned char buffer[5000];
410
    char ipaddr[64];
411
    char url[64];
412
    char outfname[16];
413
  } *mem;
414
 
712 mateusz.vi 415
  svarlang_autoload("PKGNET");
416
 
342 mateuszvis 417
  /* allocate memory */
418
  mem = malloc(sizeof(*mem));
419
  if (mem == NULL) {
712 mateusz.vi 420
    putsnls(9, 9); /* "ERROR: out of memory" */
342 mateuszvis 421
    return(1);
422
  }
423
 
211 mateuszvis 424
  /* parse command line arguments */
342 mateuszvis 425
  if (parseargv(argc, argv, mem->outfname, mem->url, &ispost) != 0) return(1);
211 mateuszvis 426
 
427
  /* if outfname requested, make sure that file does not exist yet */
342 mateuszvis 428
  if ((mem->outfname[0] != 0) && (fexists(mem->outfname))) {
712 mateusz.vi 429
    printf(svarlang_strid(0x090A), mem->outfname); /* "ERROR: file %s already exists" */
211 mateuszvis 430
    puts("");
431
    return(1);
432
  }
433
 
434
  /* init network stack */
435
  if (net_init() != 0) {
712 mateusz.vi 436
    putsnls(9, 11); /* "ERROR: Network subsystem initialization failed" */
211 mateuszvis 437
    return(1);
438
  }
439
 
440
  puts(""); /* required because watt-32 likes to print out garbage sometimes ("configuring through DHCP...") */
441
 
342 mateuszvis 442
  if (net_dnsresolve(mem->ipaddr, HOSTADDR) != 0) {
712 mateusz.vi 443
    putsnls(9, 12); /* "ERROR: DNS resolution failed" */
211 mateuszvis 444
    return(1);
445
  }
446
 
342 mateuszvis 447
  flen = htget(mem->ipaddr, mem->url, mem->outfname, &bsum, ispost, mem->buffer, sizeof(mem->buffer));
211 mateuszvis 448
  if (flen < 1) return(1);
449
 
342 mateuszvis 450
  if (mem->outfname[0] != 0) {
209 mateuszvis 451
    /* print bsum, size, filename */
712 mateusz.vi 452
    printf(svarlang_strid(0x0200), flen >> 10, mem->outfname, bsum); /* Downloaded %ld KiB into %s (BSUM: %04X) */
209 mateuszvis 453
    puts("");
454
  }
455
 
207 mateuszvis 456
  return(0);
457
}