Esempio n. 1
1
int NFC_Mifare_Classic(int argc, const char *argv[]) //! Lecture - Écriture d'une carte MIFARE Classic
{
    action_t atAction = ACTION_USAGE;
    uint8_t *pbtUID;
    int    unlock = 0;
    if (argc < 2)
    {
        sprintf(message_erreur,"Syntaxe incorrecte !");
        return EXIT_FAILURE; //! Échec !
    }
    const char *command = argv[1];
    if (strcmp(command, "r") == 0 || strcmp(command, "R") == 0)
    {
        if (argc < 4)
        {
            sprintf(message_erreur,"Syntaxe incorrecte !");
            return EXIT_FAILURE; //! Échec !
        }
        atAction = ACTION_READ;
        if (strcmp(command, "R") == 0)
        {
            unlock = 1;
        }
        bUseKeyA = tolower((int)((unsigned char) * (argv[2]))) == 'a';
        bTolerateFailures = tolower((int)((unsigned char) * (argv[2]))) != (int)((unsigned char) * (argv[2]));
        bUseKeyFile = (argc > 4);
        bForceKeyFile = ((argc > 5) && (strcmp((char *)argv[5], "f") == 0));
    }
    else if (strcmp(command, "w") == 0 || strcmp(command, "W") == 0)
    {
        if (argc < 4)
        {
            sprintf(message_erreur,"Syntaxe incorrecte !");
            return EXIT_FAILURE; //! Échec !
        }
        atAction = ACTION_WRITE;
        if (strcmp(command, "W") == 0)
        {
            unlock = 1;
        }
        bUseKeyA = tolower((int)((unsigned char) * (argv[2]))) == 'a';
        bTolerateFailures = tolower((int)((unsigned char) * (argv[2]))) != (int)((unsigned char) * (argv[2]));
        bUseKeyFile = (argc > 4);
        bForceKeyFile = ((argc > 5) && (strcmp((char *)argv[5], "f") == 0));
    }
    if (atAction == ACTION_USAGE)
    {
        sprintf(message_erreur,"Syntaxe incorrecte !");
        return EXIT_FAILURE; //! Échec !
    }
    //! We don't know yet the card size so let's read only the UID from the keyfile for the moment
    if (bUseKeyFile)
    {
        FILE *pfKeys = fopen(argv[4], "rb");
        if (pfKeys == NULL)
        {
            sprintf(message_erreur,"Could not open keys file: %s\n", argv[4]);
            return EXIT_FAILURE; //! Échec !
        }
        if (fread(&mtKeys, 1, 4, pfKeys) != 4)
        {
            sprintf(message_erreur,"Could not read UID from key file: %s !", argv[4]);
            fclose(pfKeys);
            return EXIT_FAILURE; //! Échec !
        }
        fclose(pfKeys);
    }
    nfc_init(&context);
    if (context == NULL)
    {
        sprintf(message_erreur,"Unable to init libnfc (malloc) !");
        return EXIT_FAILURE; //! Échec !
    }
    //! Try to open the NFC reader
    pnd = nfc_open(context, NULL);
    if (pnd == NULL)
    {
        sprintf(message_erreur,"Error opening NFC reader !");
        nfc_exit(context);
        return EXIT_FAILURE; //! Échec !
    }
    if (nfc_initiator_init(pnd) < 0)
    {
        nfc_perror(pnd, "nfc_initiator_init");
        nfc_strerror_r(pnd, message_erreur, TAILLE_MESSAGE_ERREUR);
        nfc_close(pnd);
        nfc_exit(context);
        return EXIT_FAILURE; //! Échec !
    };
    //! Let the reader only try once to find a tag
    if (nfc_device_set_property_bool(pnd, NP_INFINITE_SELECT, false) < 0)
    {
        nfc_perror(pnd, "nfc_device_set_property_bool");
        nfc_strerror_r(pnd, message_erreur, TAILLE_MESSAGE_ERREUR);
        nfc_close(pnd);
        nfc_exit(context);
        return EXIT_FAILURE; //! Échec !
    }
    //! Disable ISO14443-4 switching in order to read devices that emulate Mifare Classic with ISO14443-4 compliance.
    nfc_device_set_property_bool(pnd, NP_AUTO_ISO14443_4, false);
    #ifdef DEBUG_PRINTF
    fprintf(stderr,"NFC reader: %s opened\n", nfc_device_get_name(pnd));
    #endif
    //! Try to find a MIFARE Classic tag
    if (nfc_initiator_select_passive_target(pnd, nmMifare, NULL, 0, &nt) <= 0)
    {
        sprintf(message_erreur,"Error: no tag was found !");
        nfc_close(pnd);
        nfc_exit(context);
        return EXIT_FAILURE; //! Échec !
    }
    //! Test if we are dealing with a MIFARE compatible tag
    if ((nt.nti.nai.btSak & 0x08) == 0)
    {
        #ifdef DEBUG_PRINTF
        fprintf(stderr,"Warning: tag is probably not a MFC !");
        #endif
    }
    //! Get the info from the current tag
    pbtUID = nt.nti.nai.abtUid;
    if (bUseKeyFile)
    {
        uint8_t fileUid[4];
        memcpy(fileUid, mtKeys.amb[0].mbm.abtUID, 4);
        //! Compare if key dump UID is the same as the current tag UID, at least for the first 4 bytes
        if (memcmp(pbtUID, fileUid, 4) != 0)
        {
            #ifdef DEBUG_PRINTF
            fprintf(stderr,"Expected MIFARE Classic card with UID starting as: %02x%02x%02x%02x\n", fileUid[0], fileUid[1], fileUid[2], fileUid[3]);
            fprintf(stderr,"Got card with UID starting as:                     %02x%02x%02x%02x\n", pbtUID[0], pbtUID[1], pbtUID[2], pbtUID[3]);
            #endif
            if (! bForceKeyFile)
            {
                sprintf(message_erreur,"Aborting !");
                nfc_close(pnd);
                nfc_exit(context);
                return EXIT_FAILURE; //! Échec !
            }
        }
    }
    #ifdef DEBUG_PRINTF
    fprintf(stderr,"Found MIFARE Classic card:\n");
    #endif
    print_nfc_target(&nt, false);
    //! Guessing size
    if ((nt.nti.nai.abtAtqa[1] & 0x02) == 0x02)
        //! 4K
        uiBlocks = 0xff;
    else if ((nt.nti.nai.btSak & 0x01) == 0x01)
        //! 320b
        uiBlocks = 0x13;
    else
        //! 1K/2K, checked through RATS
        uiBlocks = 0x3f;
    //! Testing RATS
    int res;
    if ((res = get_rats()) > 0)
    {
        if ((res >= 10) && (abtRx[5] == 0xc1) && (abtRx[6] == 0x05) && (abtRx[7] == 0x2f) && (abtRx[8] == 0x2f) && ((nt.nti.nai.abtAtqa[1] & 0x02) == 0x00))
        {
            //! MIFARE Plus 2K
            uiBlocks = 0x7f;
        }
        //! Chinese magic emulation card, ATS=0978009102:dabc1910
        if ((res == 9)  && (abtRx[5] == 0xda) && (abtRx[6] == 0xbc) && (abtRx[7] == 0x19) && (abtRx[8] == 0x10))
        {
            magic2 = true;
        }
    }
    #ifdef DEBUG_PRINTF
    fprintf(stderr,"Guessing size: seems to be a %i-byte card\n", (uiBlocks + 1) * 16);
    #endif
    if (bUseKeyFile)
    {
        FILE *pfKeys = fopen(argv[4], "rb");
        if (pfKeys == NULL)
        {
            sprintf(message_erreur,"Could not open keys file: %s !", argv[4]);
            return EXIT_FAILURE; //! Échec !
        }
        if (fread(&mtKeys, 1, (uiBlocks + 1) * sizeof(mifare_classic_block), pfKeys) != (uiBlocks + 1) * sizeof(mifare_classic_block))
        {
            sprintf(message_erreur,"Could not read keys file: %s !", argv[4]);
            fclose(pfKeys);
            return EXIT_FAILURE; //! Échec !
        }
        fclose(pfKeys);
    }
    if (atAction == ACTION_READ)
    {
        memset(&mtDump, 0x00, sizeof(mtDump));
    }
    else
    {
        FILE *pfDump = fopen(argv[3], "rb");
        if (pfDump == NULL)
        {
            sprintf(message_erreur,"Could not open dump file: %s !", argv[3]);
            return EXIT_FAILURE; //! Échec !
        }
        if (fread(&mtDump, 1, (uiBlocks + 1) * sizeof(mifare_classic_block), pfDump) != (uiBlocks + 1) * sizeof(mifare_classic_block))
        {
            sprintf(message_erreur,"Could not read dump file: %s !", argv[3]);
            fclose(pfDump);
            return EXIT_FAILURE; //! Échec !
        }
        fclose(pfDump);
    }
    if (atAction == ACTION_READ)
    {
        if (read_card(unlock))
        {
            #ifdef DEBUG_PRINTF
            fprintf(stderr,"Writing data to file: %s ...", argv[3]);
            #endif
            fflush(stdout);
            FILE *pfDump = fopen(argv[3], "wb");
            if (pfDump == NULL)
            {
                sprintf(message_erreur,"Could not open dump file: %s !", argv[3]);
                nfc_close(pnd);
                nfc_exit(context);
                return EXIT_FAILURE; //! Échec !
            }
            if (fwrite(&mtDump, 1, (uiBlocks + 1) * sizeof(mifare_classic_block), pfDump) != ((uiBlocks + 1) * sizeof(mifare_classic_block)))
            {
                sprintf(message_erreur,"\nCould not write to file: %s !", argv[3]);
                fclose(pfDump);
                nfc_close(pnd);
                nfc_exit(context);
                return EXIT_FAILURE; //! Échec !
            }
            #ifdef DEBUG_PRINTF
            fprintf(stderr,"Done.\n");
            #endif
            fclose(pfDump);
        }
        else
        {
            nfc_close(pnd);
            nfc_exit(context);
            return EXIT_FAILURE;
        }
    }
    else if (atAction == ACTION_WRITE)
    {
        write_card(unlock);
    }
    nfc_close(pnd);
    nfc_exit(context);
    return EXIT_SUCCESS; //! Succès !
}
Esempio n. 2
0
int main(int argc, char **argv) {
  card_t opponent[5];
  card_t dealer[5];
  card_t crib[5];
  card_t starter;
  int i;
  int hand = 0;
  
  while (1) {
    hand ++;
    for (i = 0; i < 4; i++) 
      if (!read_card(opponent + i)) 
	return 0;
    for (i = 0; i < 4; i++) 
      if (!read_card(dealer + i))
	return 0;
    for (i = 0; i < 4; i++) 
      if (!read_card(crib + i))
	return 0;
    if (!read_card(&starter))
	return 0;
    
    opponent[4] = starter;
    dealer[4] = starter;
    crib[4] = starter;
    
    printf("Hand %u:\n",hand);
    printf("Opponent's hand scores %u\n",score_hand(opponent));
    printf("Dealer's hand scores %u\n",score_hand(dealer));
    printf("Crib scores %u\n",score_hand(crib));
    printf("\n");
 
  }
}
Esempio n. 3
0
void recover(unsigned char data[], int size) 
{
    int beginning_picture = 0;
    int counter = 1;
    int card_length;
    unsigned char *card = read_card("card.raw", &card_length);
    // 10,200,224 bytes


    for (long i = 0; i < size; i++) // 27 pictures
    {   
        if ((data[i] == 0xff) &&
           (data[(i + 1)] == 0xd8) &&   
           (data[(i + 2)] == 0xff) &&
           ((data[(i + 3)] == 0xe0) || data[(i + 3)] == 0xe1))
        {
                printf("ffd8ffe0(e1) begins in file %ld\n", i);
                printf("#%d\n", counter);
                counter++;
        }
        
        if ((data[i] == 0xff) && (data[i + 1] == 0xd9))
        {
            printf("ffd9 begins in file %ld\n", i);
        }
    }
    
// while (i < size) for entire array, while loop to find beginning of jpg, while loop to find end of of jpg. 


    for(long i = 3109376; i < 3353077; i++)
    {
        save_jpeg(card, (3353077 - 3109376) + 1, "jpeg01");
    }
}
Esempio n. 4
0
static int read_int_array(struct dsa *dsa, char *name, char *fmt,
      int n, int val[])
{     int k, pos;
      char str[80+1];
      if (parse_fmt(dsa, fmt)) return 1;
      if (!(dsa->fmt_f == 'I' && dsa->fmt_w <= 80 &&
            dsa->fmt_k * dsa->fmt_w <= 80))
      {  xprintf(
            "%s:%d: can't read array '%s' - invalid format '%s'\n",
            dsa->fname, dsa->seqn, name, fmt);
         return 1;
      }
      for (k = 1, pos = INT_MAX; k <= n; k++, pos++)
      {  if (pos >= dsa->fmt_k)
         {  if (read_card(dsa)) return 1;
            pos = 0;
         }
         memcpy(str, dsa->card + dsa->fmt_w * pos, dsa->fmt_w);
         str[dsa->fmt_w] = '\0';
         strspx(str);
         if (str2int(str, &val[k]))
         {  xprintf(
               "%s:%d: can't read array '%s' - invalid value '%s'\n",
               dsa->fname, dsa->seqn, name, str);
            return 1;
         }
      }
      return 0;
}
Esempio n. 5
0
t_stat cdr_boot (int32 unitno, DEVICE *dptr)
{
cdr_ebcdic = 1;
DAR = 0;
LCR = 80;
read_card(0, 1);
return SCPE_OK;
}
Esempio n. 6
0
card* duel::new_card(uint32 code) {
	card* pcard = new card(this);
	cards.insert(pcard);
	if (code)
	{
		if (creader)
			read_duel_card(this, code, &(pcard->data));
		else
			read_card(code, &(pcard->data));
	}
	pcard->data.code = code;
	lua->register_card(pcard);
	return pcard;
}
Esempio n. 7
0
static int read_real_array(struct dsa *dsa, char *name, char *fmt,
      int n, double val[])
{     int k, pos;
      char str[80+1], *ptr;
      if (parse_fmt(dsa, fmt)) return 1;
      if (!(dsa->fmt_f != 'I' && dsa->fmt_w <= 80 &&
            dsa->fmt_k * dsa->fmt_w <= 80))
      {  xprintf(
            "%s:%d: can't read array '%s' - invalid format '%s'\n",
            dsa->fname, dsa->seqn, name, fmt);
         return 1;
      }
      for (k = 1, pos = INT_MAX; k <= n; k++, pos++)
      {  if (pos >= dsa->fmt_k)
         {  if (read_card(dsa)) return 1;
            pos = 0;
         }
         memcpy(str, dsa->card + dsa->fmt_w * pos, dsa->fmt_w);
         str[dsa->fmt_w] = '\0';
         strspx(str);
         if (strchr(str, '.') == NULL && strcmp(str, "0"))
         {  xprintf("%s(%d): can't read array '%s' - value '%s' has no "
               "decimal point\n", dsa->fname, dsa->seqn, name, str);
            return 1;
         }
         /* sometimes lower case letters appear */
         for (ptr = str; *ptr; ptr++)
            *ptr = (char)toupper((unsigned char)*ptr);
         ptr = strchr(str, 'D');
         if (ptr != NULL) *ptr = 'E';
         /* value may appear with decimal exponent but without letters
            E or D (for example, -123.456-012), so missing letter should
            be inserted */
         ptr = strchr(str+1, '+');
         if (ptr == NULL) ptr = strchr(str+1, '-');
         if (ptr != NULL && *(ptr-1) != 'E')
         {  xassert(strlen(str) < 80);
            memmove(ptr+1, ptr, strlen(ptr)+1);
            *ptr = 'E';
         }
         if (str2num(str, &val[k]))
         {  xprintf(
               "%s:%d: can't read array '%s' - invalid value '%s'\n",
               dsa->fname, dsa->seqn, name, str);
            return 1;
         }
      }
      return 0;
}
Esempio n. 8
0
int main()
{
    int card_length;
    unsigned char *card = read_card("card.raw", &card_length);
    
// 3109376, 3633664, 3895808, 4157952, 4420096, 4682240, 4911616, 5173760, 5435904, 5698048, 5960192, 6222336, 6484480
// 6746624, 7008768, 7270912, 7533056, 7795200, 8057344, 8319488, 8581632, 8843776, 9105920, 9368064, 9630208, 9892352

    // recover(card, card_length);  
    save_jpeg(&card[3109376], (3353077-3109376)+1, "jpeg01");
    save_jpeg(&card[3371520], (3621114-3371520)+1, "jpeg02");
    save_jpeg(&card[3633664], (3887298-3633664)+1, "jpeg03");
    save_jpeg(&card[3895808], (4136893-3895808)+1, "jpeg04");
    save_jpeg(&card[4157952], (4412860-4157952)+1, "jpeg05");        
    
    save_jpeg(&card[4420096], (4671886-4420096)+1, "jpeg06");
    save_jpeg(&card[4682240], (4910537-4682240)+1, "jpeg07");
    save_jpeg(&card[4911616], (5157123-4911616)+1, "jpeg08");
    save_jpeg(&card[5173760], (5408874-5173760)+1, "jpeg09");
    save_jpeg(&card[5435904], (5684621-5435904)+1, "jpeg10");

    save_jpeg(&card[5698048], (5937804-5698048)+1, "jpeg11");
    save_jpeg(&card[5960192], (6204898-5960192)+1, "jpeg12");
    save_jpeg(&card[6222336], (6464235-6222336)+1, "jpeg13");
    save_jpeg(&card[6484480], (6728616-6484480)+1, "jpeg14");
    save_jpeg(&card[6746624], (6994343-6746624)+1, "jpeg15");
    
    save_jpeg(&card[7008768], (7263145-7008768)+1, "jpeg16");        
    save_jpeg(&card[7270912], (7517331-7270912)+1, "jpeg17");
    save_jpeg(&card[7533056], (7770019-7533056)+1, "jpeg18");
    save_jpeg(&card[7795200], (8041577-7795200)+1, "jpeg19");
    save_jpeg(&card[8057344], (8302006-8057344)+1, "jpeg20");

    save_jpeg(&card[8319488], (8564074-8319488)+1, "jpeg21");        
    save_jpeg(&card[8581632], (8824826-8581632)+1, "jpeg22");
    save_jpeg(&card[8843776], (9087563-8843776)+1, "jpeg23");
    save_jpeg(&card[9105920], (9346565-9105920)+1, "jpeg24");
    save_jpeg(&card[9368064], (9613420-9368064)+1, "jpeg25");
    save_jpeg(&card[9630208], (9868563-9630208)+1, "jpeg26");
    save_jpeg(&card[9892352], (10134695-982352)+1, "jpeg27");        
}
Esempio n. 9
0
bool psxcard_device::transfer(uint8_t to, uint8_t *from)
{
	bool ret=true;

	switch (state)
	{
		case state_illegal:
			if (is_loaded())
			{
//              printf("CARD: begin\n");
				state = state_command;
				*from = 0x00;
			}
			else
			{
				ret = false;
			}
			break;

		case state_command:
			cmd=to;
			*from=0x5a;
			state=state_cmdack;
			break;

		case state_cmdack:
			*from=0x5d;
			state=state_wait;
			break;

		case state_wait:
			*from=0x00;
			state=state_addr_hi;
			break;

		case state_addr_hi:
			addr=(to<<8);
//          printf("addr_hi: %02x, addr = %x\n", to, addr);
			*from=to;
			state=state_addr_lo;
			break;

		case state_addr_lo:
			addr|=(to&0xff);
//          printf("addr_lo: %02x, addr = %x, cmd = %x\n", to, addr, cmd);

			switch (cmd)
			{
				case 'R':   // 0x52
				{
					pkt[0]=*from=0x5c;
					pkt[1]=0x5d;
					pkt[2]=(addr>>8);
					pkt[3]=(addr&0xff);
					read_card(addr,&pkt[4]);
					pkt[4+128]=checksum_data(&pkt[2],128+2);
					pkt[5+128]=0x47;
					pkt_sz=6+128;
					pkt_ptr=1;
					state=state_read;
					break;
				}
				case 'W':   // 0x57
				{
					pkt[0]=addr>>8;
					pkt[1]=addr&0xff;
					pkt_sz=129+2;
					pkt_ptr=2;
					state=state_write;
					*from=to;
					break;
				}
				default:
					state=state_illegal;
					break;
			}
			break;

		case state_read:
			//assert(to==0);
//          printf("state_read: pkt_ptr = %d, pkt_sz = %d\n", pkt_ptr, pkt_sz);
			*from=pkt[pkt_ptr++];
			if (pkt_ptr==pkt_sz)
			{
				#ifdef debug_card
					printf("card: read finished\n");
				#endif

				state=state_end;
			}
			break;

		case state_write:
			*from=to;
			pkt[pkt_ptr++]=to;
			if (pkt_ptr==pkt_sz)
			{
				*from=0x5c;
				state=state_writeack_2;
			}
			break;

		case state_writeack_2:
			*from=0x5d;
			state=state_writechk;
			break;

		case state_writechk:
		{
			unsigned char chk=checksum_data(pkt,128+2);
			if (chk==pkt[128+2])
			{
				#ifdef debug_card
					printf("card: write ok\n");
				#endif

				write_card(addr,pkt+2);

				*from='G';
			} else
			{
				#ifdef debug_card
					printf("card: write fail\n");
				#endif

				*from='N';
			}
			state=state_end;
			break;
		}

		case state_end:
			ret = false;
			state = state_illegal;
			break;

		default: /*assert(0);*/ ret=false; break;
	}

	#ifdef debug_card
//      printf("card: transfer to=%02x from=%02x ret=%c\n",to,*from,ret ? 'T' : 'F');
	#endif

	return ret;
}
Esempio n. 10
0
int32 crd (int32 op, int32 m, int32 n, int32 data)
{
    int32 iodata;
    switch (op) {
        case 0:                                         /* SIO 1442 */
            /* if (n == 1)
                return STOP_IBKPT; */
            switch (data) {                             /* Select stacker */
                case 0x00:
                    break;
                case 0x01:
                    s2sel = 1;
                    break;
                default:
                    break;
            }                                       
            switch (n) {
                case 0x00:                              /* Feed */
                    iodata = SCPE_OK;
                    break;  
                case 0x01:                              /* Read only */
                    if (cdr_ebcdic)
                        iodata = read_card(0, 1);
                        else
                        iodata = read_card(0, 0);
                    break;
                case 0x02:                              /* Punch and feed */
                    iodata = punch_card(0, 0);
                    break;
                case 0x03:                              /* Read Col Binary */
                    iodata = read_card(0, 1);
                    break;
                case 0x04:                              /* Punch no feed */
                    iodata = punch_card(0, 1);
                    break;
                default:
                    return STOP_INVDEV;
            }
            return iodata;
        case 1:                                         /* LIO 1442 */
            switch (n) {
                case 0x00:                              /* Load LCR */
                    LCR = data & 0xffff;
                    break;
                case 0x04:
                    DAR = data & 0xffff;
                    break;
                default:
                    return STOP_INVDEV;
            }
            return SCPE_OK;
        case 2:                                         /* TIO 1442 */
            iodata = 0;
            switch (n) {
                case 0x00:                              /* Error */
                    if (carderr || pcherror || notready)
                        iodata = 1;
                    if ((cdr_unit.flags & UNIT_ATT) == 0) 
                        iodata = 1;                     /* attached? */
                    break;
                case 0x02:                              /* Busy */
                    if (sim_is_active (&cdr_unit)) 
                        iodata = 1;
                    break;  
                default:
                    return (STOP_INVDEV << 16);
            }                       
            return ((SCPE_OK << 16) | iodata);
        case 3:                                         /* SNS 1442 */
            iodata = 0;
            switch (n) {
                case 0x01:
                    break;
                case 0x02:
                    break;
                case 0x03:
                    if (carderr)
                        iodata |= 0x80;
                    if (lastcard)
                        iodata |= 0x40;
                    if (pcherror)
                        iodata |= 0x20;
                    if ((cdr_unit.flags & UNIT_ATT) == 0) 
                        iodata |= 0x08;
                    if (notready)
                        iodata |= 0x08; 
                    break;
                case 0x04:
                    iodata = DAR;
                    break;  
                default:
                    return (STOP_INVDEV << 16);
            }
            iodata |= ((SCPE_OK << 16) & 0xffff0000);        
            return (iodata);
        case 4:                                         /* APL 1442 */
            iodata = 0;
            switch (n) {
                case 0x00:                              /* Error */
                    if (carderr || pcherror || notready)
                        iodata = 1;
                    if ((cdr_unit.flags & UNIT_ATT) == 0) 
                        iodata = 1;                     /* attached? */
                    break;
                case 0x02:                              /* Busy */
                    if (sim_is_active (&cdr_unit)) 
                        iodata = 1;
                    break;  
                default:
                    return (STOP_INVDEV << 16);
            }                       
            return ((SCPE_OK << 16) | iodata);
        default:
            break;
    }                       
    printf (">>CRD non-existent function %d\n", op);
    return SCPE_OK;                     
}
Esempio n. 11
0
int
main (int argc, const char *argv[])
{
  bool    bReadAction;
  FILE   *pfDump;

  if (argc < 3) {
    printf ("\n");
    printf ("%s r|w <dump.mfd>\n", argv[0]);
    printf ("\n");
    printf ("r|w         - Perform read from or write to card\n");
    printf ("<dump.mfd>  - MiFare Dump (MFD) used to write (card to MFD) or (MFD to card)\n");
    printf ("\n");
    return 1;
  }

  DBG ("\nChecking arguments and settings\n");

  bReadAction = tolower ((int) ((unsigned char) *(argv[1])) == 'r');

  if (bReadAction) {
    memset (&mtDump, 0x00, sizeof (mtDump));
  } else {
    pfDump = fopen (argv[2], "rb");

    if (pfDump == NULL) {
      ERR ("Could not open dump file: %s\n", argv[2]);
      return 1;
    }

    if (fread (&mtDump, 1, sizeof (mtDump), pfDump) != sizeof (mtDump)) {
      ERR ("Could not read from dump file: %s\n", argv[2]);
      fclose (pfDump);
      return 1;
    }
    fclose (pfDump);
  }
  DBG ("Successfully opened the dump file\n");

  // Try to open the NFC device
  pnd = nfc_connect (NULL);
  if (pnd == NULL) {
    ERR ("Error connecting NFC device\n");
    return 1;
  }

  nfc_initiator_init (pnd);

  // Drop the field for a while
  if (!nfc_configure (pnd, NDO_ACTIVATE_FIELD, false)) {
    nfc_perror (pnd, "nfc_configure");
    exit (EXIT_FAILURE);
  }
  // Let the device only try once to find a tag
  if (!nfc_configure (pnd, NDO_INFINITE_SELECT, false)) {
    nfc_perror (pnd, "nfc_configure");
    exit (EXIT_FAILURE);
  }
  if (!nfc_configure (pnd, NDO_HANDLE_CRC, true)) {
    nfc_perror (pnd, "nfc_configure");
    exit (EXIT_FAILURE);
  }
  if (!nfc_configure (pnd, NDO_HANDLE_PARITY, true)) {
    nfc_perror (pnd, "nfc_configure");
    exit (EXIT_FAILURE);
  }
  // Enable field so more power consuming cards can power themselves up
  if (!nfc_configure (pnd, NDO_ACTIVATE_FIELD, true)) {
    nfc_perror (pnd, "nfc_configure");
    exit (EXIT_FAILURE);
  }

  printf ("Connected to NFC device: %s\n", pnd->acName);

  // Try to find a MIFARE Ultralight tag
  if (!nfc_initiator_select_passive_target (pnd, nmMifare, NULL, 0, &nt)) {
    ERR ("no tag was found\n");
    nfc_disconnect (pnd);
    return 1;
  }
  // Test if we are dealing with a MIFARE compatible tag

  if (nt.nti.nai.abtAtqa[1] != 0x44) {
    ERR ("tag is not a MIFARE Ultralight card\n");
    nfc_disconnect (pnd);
    return EXIT_FAILURE;
  }
  // Get the info from the current tag
  printf ("Found MIFARE Ultralight card with UID: ");
  size_t  szPos;
  for (szPos = 0; szPos < nt.nti.nai.szUidLen; szPos++) {
    printf ("%02x", nt.nti.nai.abtUid[szPos]);
  }
  printf("\n");

  if (bReadAction) {
    if (read_card ()) {
      printf ("Writing data to file: %s ... ", argv[2]);
      fflush (stdout);
      pfDump = fopen (argv[2], "wb");
      if (pfDump == NULL) {
        printf ("Could not open file: %s\n", argv[2]);
        return EXIT_FAILURE;
      }
      if (fwrite (&mtDump, 1, sizeof (mtDump), pfDump) != sizeof (mtDump)) {
        printf ("Could not write to file: %s\n", argv[2]);
        return EXIT_FAILURE;
      }
      fclose (pfDump);
      printf ("Done.\n");
    }
  } else {
    write_card ();
  }

  nfc_disconnect (pnd);

  return EXIT_SUCCESS;
}
Esempio n. 12
0
int
main(int argc, const char *argv[])
{
  bool    bReadAction;
  FILE   *pfDump;

  if (argc < 3) {
    printf("\n");
    printf("%s r|w <dump.mfd>\n", argv[0]);
    printf("\n");
    printf("r|w         - Perform read from or write to card\n");
    printf("<dump.mfd>  - MiFare Dump (MFD) used to write (card to MFD) or (MFD to card)\n");
    printf("\n");
    exit(EXIT_FAILURE);
  }

  DBG("\nChecking arguments and settings\n");

  bReadAction = tolower((int)((unsigned char) * (argv[1])) == 'r');

  if (bReadAction) {
    memset(&mtDump, 0x00, sizeof(mtDump));
  } else {
    pfDump = fopen(argv[2], "rb");

    if (pfDump == NULL) {
      ERR("Could not open dump file: %s\n", argv[2]);
      exit(EXIT_FAILURE);
    }

    if (fread(&mtDump, 1, sizeof(mtDump), pfDump) != sizeof(mtDump)) {
      ERR("Could not read from dump file: %s\n", argv[2]);
      fclose(pfDump);
      exit(EXIT_FAILURE);
    }
    fclose(pfDump);
  }
  DBG("Successfully opened the dump file\n");

  nfc_context *context;
  nfc_init(&context);
  if (context == NULL) {
    ERR("Unable to init libnfc (malloc)");
    exit(EXIT_FAILURE);
  }

  // Try to open the NFC device
  pnd = nfc_open(context, NULL);
  if (pnd == NULL) {
    ERR("Error opening NFC device");
    nfc_exit(context);
    exit(EXIT_FAILURE);
  }

  if (nfc_initiator_init(pnd) < 0) {
    nfc_perror(pnd, "nfc_initiator_init");
    nfc_close(pnd);
    nfc_exit(context);
    exit(EXIT_FAILURE);
  }

  // Let the device only try once to find a tag
  if (nfc_device_set_property_bool(pnd, NP_INFINITE_SELECT, false) < 0) {
    nfc_perror(pnd, "nfc_device_set_property_bool");
    nfc_close(pnd);
    nfc_exit(context);
    exit(EXIT_FAILURE);
  }

  printf("NFC device: %s opened\n", nfc_device_get_name(pnd));

  // Try to find a MIFARE Ultralight tag
  if (nfc_initiator_select_passive_target(pnd, nmMifare, NULL, 0, &nt) <= 0) {
    ERR("no tag was found\n");
    nfc_close(pnd);
    nfc_exit(context);
    exit(EXIT_FAILURE);
  }
  // Test if we are dealing with a MIFARE compatible tag

  if (nt.nti.nai.abtAtqa[1] != 0x44) {
    ERR("tag is not a MIFARE Ultralight card\n");
    nfc_close(pnd);
    nfc_exit(context);
    exit(EXIT_FAILURE);
  }
  // Get the info from the current tag
  printf("Found MIFARE Ultralight card with UID: ");
  size_t  szPos;
  for (szPos = 0; szPos < nt.nti.nai.szUidLen; szPos++) {
    printf("%02x", nt.nti.nai.abtUid[szPos]);
  }
  printf("\n");

  if (bReadAction) {
    if (read_card()) {
      printf("Writing data to file: %s ... ", argv[2]);
      fflush(stdout);
      pfDump = fopen(argv[2], "wb");
      if (pfDump == NULL) {
        printf("Could not open file: %s\n", argv[2]);
        nfc_close(pnd);
        nfc_exit(context);
        exit(EXIT_FAILURE);
      }
      if (fwrite(&mtDump, 1, sizeof(mtDump), pfDump) != sizeof(mtDump)) {
        printf("Could not write to file: %s\n", argv[2]);
        fclose(pfDump);
        nfc_close(pnd);
        nfc_exit(context);
        exit(EXIT_FAILURE);
      }
      fclose(pfDump);
      printf("Done.\n");
    }
  } else {
    write_card();
  }

  nfc_close(pnd);
  nfc_exit(context);
  exit(EXIT_SUCCESS);
}
Esempio n. 13
0
int
main(int argc, const char *argv[])
{
  int     iAction = 0;
  uint8_t iUID[MAX_UID_LEN] = { 0x0 };
  size_t  szUID = 0;
  bool    bOTP = false;
  bool    bLock = false;
  bool    bUID = false;
  FILE   *pfDump;

  if (argc < 2) {
      print_usage(argv);
      exit(EXIT_FAILURE);
  }

  DBG("\nChecking arguments and settings\n");

  // Get commandline options
  for (int arg = 1; arg < argc; arg++) {
    if (0 == strcmp(argv[arg], "r")) {
      iAction = 1;
    } else if (0 == strcmp(argv[arg], "w")) {
      iAction = 2;
    } else if (0 == strcmp(argv[arg], "--with-uid")) {
      if (argc < 5) {
        ERR("Please supply a UID of 4, 7 or 10 bytes long. Ex: a1:b2:c3:d4");
        exit(EXIT_FAILURE);
      }
      szUID = str_to_uid(argv[4], iUID);
    } else if (0 == strcmp(argv[arg], "--full")) {
      bOTP = true;
      bLock = true;
      bUID = true;
    } else if (0 == strcmp(argv[arg], "--otp")) {
      bOTP = true;
    } else if (0 == strcmp(argv[arg], "--lock")) {
      bLock = true;
    } else if (0 == strcmp(argv[arg], "--uid")) {
      bUID = true;
    } else if (0 == strcmp(argv[arg], "--check-magic")) {
      iAction = 3;
    } else {
      //Skip validation of the filename
      if ((arg != 2) && (arg != 4)) {
        ERR("%s is not supported option.", argv[arg]);
        print_usage(argv);
        exit(EXIT_FAILURE);
      }
    }
  }

  if (iAction == 1) {
    memset(&mtDump, 0x00, sizeof(mtDump));
  } else if (iAction == 2) {
    pfDump = fopen(argv[2], "rb");

    if (pfDump == NULL) {
      ERR("Could not open dump file: %s\n", argv[2]);
      exit(EXIT_FAILURE);
    }

    if (fread(&mtDump, 1, sizeof(mtDump), pfDump) != sizeof(mtDump)) {
      ERR("Could not read from dump file: %s\n", argv[2]);
      fclose(pfDump);
      exit(EXIT_FAILURE);
    }
    fclose(pfDump);
    DBG("Successfully opened the dump file\n");
  } else if (iAction == 3) {
    DBG("Switching to Check Magic Mode\n");
  } else {
    ERR("Unable to determine operating mode");
    exit(EXIT_FAILURE);
  }

  nfc_context *context;
  nfc_init(&context);
  if (context == NULL) {
    ERR("Unable to init libnfc (malloc)");
    exit(EXIT_FAILURE);
  }

  // Try to open the NFC device
  pnd = nfc_open(context, NULL);
  if (pnd == NULL) {
    ERR("Error opening NFC device");
    nfc_exit(context);
    exit(EXIT_FAILURE);
  }
  printf("NFC device: %s opened\n", nfc_device_get_name(pnd));

  if (list_passive_targets(pnd)) {
    nfc_perror(pnd, "nfc_device_set_property_bool");
    nfc_close(pnd);
    nfc_exit(context);
    exit(EXIT_FAILURE);
  }

  if (nfc_initiator_init(pnd) < 0) {
    nfc_perror(pnd, "nfc_initiator_init");
    nfc_close(pnd);
    nfc_exit(context);
    exit(EXIT_FAILURE);
  }

  // Let the device only try once to find a tag
  if (nfc_device_set_property_bool(pnd, NP_INFINITE_SELECT, false) < 0) {
    nfc_perror(pnd, "nfc_device_set_property_bool");
    nfc_close(pnd);
    nfc_exit(context);
    exit(EXIT_FAILURE);
  }

  // Try to find a MIFARE Ultralight tag
  if (nfc_initiator_select_passive_target(pnd, nmMifare, (szUID) ? iUID : NULL, szUID, &nt) <= 0) {
    ERR("no tag was found\n");
    nfc_close(pnd);
    nfc_exit(context);
    exit(EXIT_FAILURE);
  }
  // Test if we are dealing with a MIFARE compatible tag

  if (nt.nti.nai.abtAtqa[1] != 0x44) {
    ERR("tag is not a MIFARE Ultralight card\n");
    nfc_close(pnd);
    nfc_exit(context);
    exit(EXIT_FAILURE);
  }
  // Get the info from the current tag
  printf("Using MIFARE Ultralight card with UID: ");
  size_t  szPos;
  for (szPos = 0; szPos < nt.nti.nai.szUidLen; szPos++) {
    printf("%02x", nt.nti.nai.abtUid[szPos]);
  }
  printf("\n");

  if (iAction == 1) {
    if (read_card()) {
      printf("Writing data to file: %s ... ", argv[2]);
      fflush(stdout);
      pfDump = fopen(argv[2], "wb");
      if (pfDump == NULL) {
        printf("Could not open file: %s\n", argv[2]);
        nfc_close(pnd);
        nfc_exit(context);
        exit(EXIT_FAILURE);
      }
      if (fwrite(&mtDump, 1, sizeof(mtDump), pfDump) != sizeof(mtDump)) {
        printf("Could not write to file: %s\n", argv[2]);
        fclose(pfDump);
        nfc_close(pnd);
        nfc_exit(context);
        exit(EXIT_FAILURE);
      }
      fclose(pfDump);
      printf("Done.\n");
    }
  } else if (iAction == 2) {
    write_card(bOTP, bLock, bUID);
  } else if (iAction == 3) {
    if (!check_magic()) {
        printf("Card is not magic\n");
        nfc_close(pnd);
        nfc_exit(context);
        exit(EXIT_FAILURE);
    } else {
        printf("Card is magic\n");
    }
  }

  nfc_close(pnd);
  nfc_exit(context);
  exit(EXIT_SUCCESS);
}
Esempio n. 14
0
/*************************************************
  Function:         createAllDir
  Description:      穿件所有目录、文件
  Input:            无
  Output:           无
  Return:           无
  Others:
*************************************************/
void operGuiStorage::createAllDir()
{
    gui_init_storage();
    read_card();            //上电读卡信息!!!!
}
Esempio n. 15
0
int
main(int argc, const char *argv[])
{
  int     iAction = 0;
  uint8_t iDumpSize = sizeof(mifareul_tag);
  uint8_t iUID[MAX_UID_LEN] = { 0x0 };
  size_t  szUID = 0;
  bool    bOTP = false;
  bool    bLock = false;
  bool    bUID = false;
  bool    bPWD = false;
  bool    bPart = false;
  bool    bFilename = false;
  FILE   *pfDump;

  if (argc < 3) {
    print_usage(argv);
    exit(EXIT_FAILURE);
  }

  DBG("\nChecking arguments and settings\n");

  // Get commandline options
  for (int arg = 1; arg < argc; arg++) {
    if (0 == strcmp(argv[arg], "r")) {
      iAction = 1;
    } else if (0 == strcmp(argv[arg], "w")) {
      iAction = 2;
    } else if (0 == strcmp(argv[arg], "--with-uid")) {
      if (arg + 1 == argc) {
        ERR("Please supply a UID of 4, 7 or 10 bytes long. Ex: a1:b2:c3:d4");
        exit(EXIT_FAILURE);
      }
      szUID = str_to_uid(argv[++arg], iUID);
    } else if (0 == strcmp(argv[arg], "--full")) {
      bOTP = true;
      bLock = true;
      bUID = true;
    } else if (0 == strcmp(argv[arg], "--otp")) {
      bOTP = true;
    } else if (0 == strcmp(argv[arg], "--lock")) {
      bLock = true;
    } else if (0 == strcmp(argv[arg], "--uid")) {
      bUID = true;
    } else if (0 == strcmp(argv[arg], "--check-magic")) {
      iAction = 3;
    } else if (0 == strcmp(argv[arg], "--partial")) {
      bPart = true;
    } else if (0 == strcmp(argv[arg], "--pw")) {
      bPWD = true;
      if (arg + 1 == argc || strlen(argv[++arg]) != 8 || ! ev1_load_pwd(iPWD, argv[arg])) {
        ERR("Please supply a PASSWORD of 8 HEX digits");
        exit(EXIT_FAILURE);
      }
    } else {
      //Skip validation of the filename
      if (arg != 2) {
        ERR("%s is not a supported option.", argv[arg]);
        print_usage(argv);
        exit(EXIT_FAILURE);
      } else {
        bFilename = true;
      }
    }
  }
  if (! bFilename) {
    ERR("Please supply a Mifare Dump filename");
    exit(EXIT_FAILURE);
  }

  nfc_context *context;
  nfc_init(&context);
  if (context == NULL) {
    ERR("Unable to init libnfc (malloc)");
    exit(EXIT_FAILURE);
  }

  // Try to open the NFC device
  pnd = nfc_open(context, NULL);
  if (pnd == NULL) {
    ERR("Error opening NFC device");
    nfc_exit(context);
    exit(EXIT_FAILURE);
  }
  printf("NFC device: %s opened\n", nfc_device_get_name(pnd));

  if (list_passive_targets(pnd)) {
    nfc_perror(pnd, "nfc_device_set_property_bool");
    nfc_close(pnd);
    nfc_exit(context);
    exit(EXIT_FAILURE);
  }

  if (nfc_initiator_init(pnd) < 0) {
    nfc_perror(pnd, "nfc_initiator_init");
    nfc_close(pnd);
    nfc_exit(context);
    exit(EXIT_FAILURE);
  }

  // Let the device only try once to find a tag
  if (nfc_device_set_property_bool(pnd, NP_INFINITE_SELECT, false) < 0) {
    nfc_perror(pnd, "nfc_device_set_property_bool");
    nfc_close(pnd);
    nfc_exit(context);
    exit(EXIT_FAILURE);
  }

  // Try to find a MIFARE Ultralight tag
  if (nfc_initiator_select_passive_target(pnd, nmMifare, (szUID) ? iUID : NULL, szUID, &nt) <= 0) {
    ERR("no tag was found\n");
    nfc_close(pnd);
    nfc_exit(context);
    exit(EXIT_FAILURE);
  }

  // Test if we are dealing with a MIFARE compatible tag
  if (nt.nti.nai.abtAtqa[1] != 0x44) {
    ERR("tag is not a MIFARE Ultralight card\n");
    nfc_close(pnd);
    nfc_exit(context);
    exit(EXIT_FAILURE);
  }
  // Get the info from the current tag
  printf("Using MIFARE Ultralight card with UID: ");
  size_t  szPos;
  for (szPos = 0; szPos < nt.nti.nai.szUidLen; szPos++) {
    printf("%02x", nt.nti.nai.abtUid[szPos]);
  }
  printf("\n");

  // test if tag is EV1
  if (get_ev1_version()) {
    if (!bPWD)
      printf("Tag is EV1 - PASSWORD may be required\n");
    printf("EV1 storage size: ");
    if (abtRx[6] == 0x0b) {
      printf("48 bytes\n");
      uiBlocks = 0x14;
      iEV1Type = EV1_UL11;
      iDumpSize = sizeof(mifareul_ev1_mf0ul11_tag);
    } else if (abtRx[6] == 0x0e) {
      printf("128 bytes\n");
      uiBlocks = 0x29;
      iEV1Type = EV1_UL21;
      iDumpSize = sizeof(mifareul_ev1_mf0ul21_tag);
    } else
      printf("unknown!\n");
  } else {
    // re-init non EV1 tag
    if (nfc_initiator_select_passive_target(pnd, nmMifare, (szUID) ? iUID : NULL, szUID, &nt) <= 0) {
      ERR("no tag was found\n");
      nfc_close(pnd);
      nfc_exit(context);
      exit(EXIT_FAILURE);
    }
  }

  // EV1 login required
  if (bPWD) {
    printf("Authing with PWD: %02x%02x%02x%02x ", iPWD[0], iPWD[1], iPWD[2], iPWD[3]);
    if (!ev1_pwd_auth(iPWD)) {
      printf("\n");
      ERR("AUTH failed!\n");
      exit(EXIT_FAILURE);
    } else {
      printf("Success - PACK: %02x%02x\n", abtRx[0], abtRx[1]);
      memcpy(iPACK, abtRx, 2);
    }
  }

  if (iAction == 1) {
    memset(&mtDump, 0x00, sizeof(mtDump));
  } else if (iAction == 2) {
    pfDump = fopen(argv[2], "rb");

    if (pfDump == NULL) {
      ERR("Could not open dump file: %s\n", argv[2]);
      exit(EXIT_FAILURE);
    }

    size_t  szDump;
    if (((szDump = fread(&mtDump, 1, sizeof(mtDump), pfDump)) != iDumpSize && !bPart) || szDump <= 0) {
      ERR("Could not read from dump file or size mismatch: %s\n", argv[2]);
      fclose(pfDump);
      exit(EXIT_FAILURE);
    }
    if (szDump != iDumpSize)
      printf("Performing partial write\n");
    fclose(pfDump);
    DBG("Successfully opened the dump file\n");
  } else if (iAction == 3) {
    DBG("Switching to Check Magic Mode\n");
  } else {
    ERR("Unable to determine operating mode");
    exit(EXIT_FAILURE);
  }

  if (iAction == 1) {
    bool bRF = read_card();
    printf("Writing data to file: %s ... ", argv[2]);
    fflush(stdout);
    pfDump = fopen(argv[2], "wb");
    if (pfDump == NULL) {
      printf("Could not open file: %s\n", argv[2]);
      nfc_close(pnd);
      nfc_exit(context);
      exit(EXIT_FAILURE);
    }
    if (fwrite(&mtDump, 1, uiReadPages * 4, pfDump) != uiReadPages * 4) {
      printf("Could not write to file: %s\n", argv[2]);
      fclose(pfDump);
      nfc_close(pnd);
      nfc_exit(context);
      exit(EXIT_FAILURE);
    }
    fclose(pfDump);
    printf("Done.\n");
    if (!bRF)
      printf("Warning! Read failed - partial data written to file!\n");
  } else if (iAction == 2) {
    write_card(bOTP, bLock, bUID);
  } else if (iAction == 3) {
    if (!check_magic()) {
      printf("Card is not magic\n");
      nfc_close(pnd);
      nfc_exit(context);
      exit(EXIT_FAILURE);
    } else {
      printf("Card is magic\n");
    }
  }

  nfc_close(pnd);
  nfc_exit(context);
  exit(EXIT_SUCCESS);
}
Esempio n. 16
0
HBM *hbm_read_mat(const char *fname)
{     struct dsa _dsa, *dsa = &_dsa;
      HBM *hbm = NULL;
      dsa->fname = fname;
      xprintf("hbm_read_mat: reading matrix from '%s'...\n",
         dsa->fname);
      dsa->fp = fopen(dsa->fname, "r");
      if (dsa->fp == NULL)
      {  xprintf("hbm_read_mat: unable to open '%s' - %s\n",
            dsa->fname, strerror(errno));
         goto fail;
      }
      dsa->seqn = 0;
      hbm = xmalloc(sizeof(HBM));
      memset(hbm, 0, sizeof(HBM));
      /* read the first heading card */
      if (read_card(dsa)) goto fail;
      memcpy(hbm->title, dsa->card, 72), hbm->title[72] = '\0';
      strtrim(hbm->title);
      xprintf("%s\n", hbm->title);
      memcpy(hbm->key, dsa->card+72, 8), hbm->key[8] = '\0';
      strspx(hbm->key);
      xprintf("key = %s\n", hbm->key);
      /* read the second heading card */
      if (read_card(dsa)) goto fail;
      if (scan_int(dsa, "totcrd",  0, 14, &hbm->totcrd)) goto fail;
      if (scan_int(dsa, "ptrcrd", 14, 14, &hbm->ptrcrd)) goto fail;
      if (scan_int(dsa, "indcrd", 28, 14, &hbm->indcrd)) goto fail;
      if (scan_int(dsa, "valcrd", 42, 14, &hbm->valcrd)) goto fail;
      if (scan_int(dsa, "rhscrd", 56, 14, &hbm->rhscrd)) goto fail;
      xprintf("totcrd = %d; ptrcrd = %d; indcrd = %d; valcrd = %d; rhsc"
         "rd = %d\n", hbm->totcrd, hbm->ptrcrd, hbm->indcrd,
         hbm->valcrd, hbm->rhscrd);
      /* read the third heading card */
      if (read_card(dsa)) goto fail;
      memcpy(hbm->mxtype, dsa->card, 3), hbm->mxtype[3] = '\0';
      if (strchr("RCP",   hbm->mxtype[0]) == NULL ||
          strchr("SUHZR", hbm->mxtype[1]) == NULL ||
          strchr("AE",    hbm->mxtype[2]) == NULL)
      {  xprintf("%s:%d: matrix type '%s' not recognised\n",
            dsa->fname, dsa->seqn, hbm->mxtype);
         goto fail;
      }
      if (scan_int(dsa, "nrow", 14, 14, &hbm->nrow)) goto fail;
      if (scan_int(dsa, "ncol", 28, 14, &hbm->ncol)) goto fail;
      if (scan_int(dsa, "nnzero", 42, 14, &hbm->nnzero)) goto fail;
      if (scan_int(dsa, "neltvl", 56, 14, &hbm->neltvl)) goto fail;
      xprintf("mxtype = %s; nrow = %d; ncol = %d; nnzero = %d; neltvl ="
         " %d\n", hbm->mxtype, hbm->nrow, hbm->ncol, hbm->nnzero,
         hbm->neltvl);
      /* read the fourth heading card */
      if (read_card(dsa)) goto fail;
      memcpy(hbm->ptrfmt, dsa->card, 16), hbm->ptrfmt[16] = '\0';
      strspx(hbm->ptrfmt);
      memcpy(hbm->indfmt, dsa->card+16, 16), hbm->indfmt[16] = '\0';
      strspx(hbm->indfmt);
      memcpy(hbm->valfmt, dsa->card+32, 20), hbm->valfmt[20] = '\0';
      strspx(hbm->valfmt);
      memcpy(hbm->rhsfmt, dsa->card+52, 20), hbm->rhsfmt[20] = '\0';
      strspx(hbm->rhsfmt);
      xprintf("ptrfmt = %s; indfmt = %s; valfmt = %s; rhsfmt = %s\n",
         hbm->ptrfmt, hbm->indfmt, hbm->valfmt, hbm->rhsfmt);
      /* read the fifth heading card (optional) */
      if (hbm->rhscrd <= 0)
      {  strcpy(hbm->rhstyp, "???");
         hbm->nrhs = 0;
         hbm->nrhsix = 0;
      }
      else
      {  if (read_card(dsa)) goto fail;
         memcpy(hbm->rhstyp, dsa->card, 3), hbm->rhstyp[3] = '\0';
         if (scan_int(dsa, "nrhs", 14, 14, &hbm->nrhs)) goto fail;
         if (scan_int(dsa, "nrhsix", 28, 14, &hbm->nrhsix)) goto fail;
         xprintf("rhstyp = '%s'; nrhs = %d; nrhsix = %d\n",
            hbm->rhstyp, hbm->nrhs, hbm->nrhsix);
      }
      /* read matrix structure */
      hbm->colptr = xcalloc(1+hbm->ncol+1, sizeof(int));
      if (read_int_array(dsa, "colptr", hbm->ptrfmt, hbm->ncol+1,
         hbm->colptr)) goto fail;
      hbm->rowind = xcalloc(1+hbm->nnzero, sizeof(int));
      if (read_int_array(dsa, "rowind", hbm->indfmt, hbm->nnzero,
         hbm->rowind)) goto fail;
      /* read matrix values */
      if (hbm->valcrd <= 0) goto done;
      if (hbm->mxtype[2] == 'A')
      {  /* assembled matrix */
         hbm->values = xcalloc(1+hbm->nnzero, sizeof(double));
         if (read_real_array(dsa, "values", hbm->valfmt, hbm->nnzero,
            hbm->values)) goto fail;
      }
      else
      {  /* elemental (unassembled) matrix */
         hbm->values = xcalloc(1+hbm->neltvl, sizeof(double));
         if (read_real_array(dsa, "values", hbm->valfmt, hbm->neltvl,
            hbm->values)) goto fail;
      }
      /* read right-hand sides */
      if (hbm->nrhs <= 0) goto done;
      if (hbm->rhstyp[0] == 'F')
      {  /* dense format */
         hbm->nrhsvl = hbm->nrow * hbm->nrhs;
         hbm->rhsval = xcalloc(1+hbm->nrhsvl, sizeof(double));
         if (read_real_array(dsa, "rhsval", hbm->rhsfmt, hbm->nrhsvl,
            hbm->rhsval)) goto fail;
      }
      else if (hbm->rhstyp[0] == 'M' && hbm->mxtype[2] == 'A')
      {  /* sparse format */
         /* read pointers */
         hbm->rhsptr = xcalloc(1+hbm->nrhs+1, sizeof(int));
         if (read_int_array(dsa, "rhsptr", hbm->ptrfmt, hbm->nrhs+1,
            hbm->rhsptr)) goto fail;
         /* read sparsity pattern */
         hbm->rhsind = xcalloc(1+hbm->nrhsix, sizeof(int));
         if (read_int_array(dsa, "rhsind", hbm->indfmt, hbm->nrhsix,
            hbm->rhsind)) goto fail;
         /* read values */
         hbm->rhsval = xcalloc(1+hbm->nrhsix, sizeof(double));
         if (read_real_array(dsa, "rhsval", hbm->rhsfmt, hbm->nrhsix,
            hbm->rhsval)) goto fail;
      }
      else if (hbm->rhstyp[0] == 'M' && hbm->mxtype[2] == 'E')
      {  /* elemental format */
         hbm->rhsval = xcalloc(1+hbm->nrhsvl, sizeof(double));
         if (read_real_array(dsa, "rhsval", hbm->rhsfmt, hbm->nrhsvl,
            hbm->rhsval)) goto fail;
      }
      else
      {  xprintf("%s:%d: right-hand side type '%c' not recognised\n",
            dsa->fname, dsa->seqn, hbm->rhstyp[0]);
         goto fail;
      }
      /* read starting guesses */
      if (hbm->rhstyp[1] == 'G')
      {  hbm->nguess = hbm->nrow * hbm->nrhs;
         hbm->sguess = xcalloc(1+hbm->nguess, sizeof(double));
         if (read_real_array(dsa, "sguess", hbm->rhsfmt, hbm->nguess,
            hbm->sguess)) goto fail;
      }
      /* read solution vectors */
      if (hbm->rhstyp[2] == 'X')
      {  hbm->nexact = hbm->nrow * hbm->nrhs;
         hbm->xexact = xcalloc(1+hbm->nexact, sizeof(double));
         if (read_real_array(dsa, "xexact", hbm->rhsfmt, hbm->nexact,
            hbm->xexact)) goto fail;
      }
done: /* reading has been completed */
      xprintf("hbm_read_mat: %d cards were read\n", dsa->seqn);
      fclose(dsa->fp);
      return hbm;
fail: /* something wrong in Danish kingdom */
      if (hbm != NULL)
      {  if (hbm->colptr != NULL) xfree(hbm->colptr);
         if (hbm->rowind != NULL) xfree(hbm->rowind);
         if (hbm->rhsptr != NULL) xfree(hbm->rhsptr);
         if (hbm->rhsind != NULL) xfree(hbm->rhsind);
         if (hbm->values != NULL) xfree(hbm->values);
         if (hbm->rhsval != NULL) xfree(hbm->rhsval);
         if (hbm->sguess != NULL) xfree(hbm->sguess);
         if (hbm->xexact != NULL) xfree(hbm->xexact);
         xfree(hbm);
      }
      if (dsa->fp != NULL) fclose(dsa->fp);
      return NULL;
}