Subversion Repositories SvarDOS

Rev

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