Subversion Repositories SvarDOS

Rev

Rev 675 | Rev 725 | Go to most recent revision | Only display areas with differences | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

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